Last active
August 6, 2024 07:06
-
-
Save sunmeat/af46da22596d4d6c7246 to your computer and use it in GitHub Desktop.
regex second example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.alex.regex; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class YourClassName { | |
public static void main(String[] args) { | |
// IP адрес | |
String regexp = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; | |
// для сравнения работы find() и matches() | |
String goodIp = "192.168.0.3"; | |
String badIp = "192.168.0.3g"; | |
Pattern pattern = Pattern.compile(regexp); | |
Matcher matcher = pattern.matcher(goodIp); | |
// matches() - true, find() - true | |
matcher = pattern.matcher(badIp); | |
// matches() - false, find() - true | |
// а теперь получим дополнительную информацию | |
System.out.println(matcher.find() | |
? "I found '" + matcher.group() + "' starting at index " + matcher.start() + " and ending at index " + matcher.end() + "." | |
: "I found nothing!"); | |
// I found the text '192.168.0.3' starting at index 0 and ending at index 11 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment