String ip = "1.1.&.&";
String WILDCARD_CHARACTER = "&";
String REGEX_IP_ADDRESS_STRING = "(?:(?:"
+ WILDCARD_CHARACTER
+ "|25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:"
+ WILDCARD_CHARACTER + "|25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
Pattern p = Pattern.compile(REGEX_IP_ADDRESS_STRING1);
Matcher m = p.matcher(ip);
System.out.println("Does it match? " + m.matches());
IP Validation with the one above coded works perfectly. But I want some modifications for wildcard character which causes problem.
Current scenario :
- 192.1.&.& ------> True
- 192.1.0.1 ------> True
- & ------> False
- 192.1.& ------> False
Expect开发者_如何学JAVAed :
- 192.1.&.& ------> False
- 192.1.0.1 ------> True
- & ------> True
- 192.1.& ------> True
i.e. I want to wildcard all the inputs after a wildcard character.
What modifications in regular expression would help me achieve this? Can anyone please help it out?
I suggest the following (I have used a literal &
in this regex; of course you can change that to your + WILDCARD_CHARACTER
construct):
Pattern regex = Pattern.compile(
"^ # Anchor the match at the start of the string\n" +
"(?: # Match either...\n" +
" & # the wildcard character\n" +
" | # or a number between 0 and 255\n" +
" (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n" +
" \\. # followed by a dot, followed by...\n" +
" (?: # ...either...\n" +
" & # the wildcard character\n" +
" | # or a number etc. etc.\n" +
" (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n" +
" \\.\n" +
" (?:\n" +
" &\n" +
" |\n" +
" (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n" +
" \\.\n" +
" (?:\n" +
" &\n" +
" |\n" +
" (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n" +
" )\n" +
" )\n" +
" )\n" +
")\n" +
"$ # Anchor the match at the end of the string",
Pattern.COMMENTS);
(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d) |(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).& |(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).& |(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).& |&
All on one line should match you requirements
精彩评论