[英]find similar IP in java using java.util.regex.Pattern
I am trying to find similar IP using java.util.regex.Pattern
in java. 我试图在java中使用java.util.regex.Pattern
找到类似的IP。
String ipAddr = "192.168.112.33";
Pattern PRIVATE_ADDRESS_PATTERN = Pattern.compile("192.168.(.*?).33", Pattern.CASE_INSENSITIVE);
String IPaddress = PRIVATE_ADDRESS_PATTERN.matcher(ipAddr).toString();
It is not working for me. 它不适合我。 Where is my mistake? 我的错误在哪里?
Why you simply don't make : 为什么你根本不做:
String ipAddr = "192.168.112.33";
//If your pattern match with your String then it is correct else it is not
if (ipAddr.matches("192\\.168\\.(.*?)\\.33")) {
System.out.println("CORRECT");
} else {
System.out.println("NOT CORRECT");
}
Like @lathspell said in the comment you have to escape the dot (.) with \\\\.
就像@lathspell在评论中说的那样,你必须用\\\\.
来逃避点(。) \\\\.
A more correct matcher would be the following: 更正确的匹配器如下:
Pattern IP_PATTERN = Pattern.compile("192\\.168\\.(\\d{1,3})\\.33");
This way you would only match numbers in there and not letters, for instance. 这样,你只会匹配那里的数字,而不是字母。 According to further use cases, you may want to refine your number matcher to make sure it matches only in the range 0-255
: 根据更多用例,您可能需要优化数字匹配器以确保它仅在0-255
范围内匹配:
String IP_PATTERN_PART = "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]?)";
Pattern IP_PATTERN = Pattern.compile("192\\.168\\.("+IP_PATTERN_PART+")\\.33");
Also, if you are sure you will never get anything else than an IP (meaning no enclosing text), you may want to use the start and end delimiters: 此外,如果您确定除了IP之外永远不会得到任何其他内容(意味着没有封闭文本),您可能需要使用开始和结束分隔符:
Pattern IP_PATTERN = Pattern.compile("^192\\.168\\.(\\d{1,3})\\.33$");
Then, once you've decided which pattern to use, you'll have to use it this way: 然后,一旦你决定使用哪种模式,你就必须这样使用它:
Matcher matcher = IP_PATTERN.matcher(candidate);
String otherIP = null;
if (matcher.matches()) {
matcher.find();
otherIP = matcher.group(1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.