Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP address validation with wildcard character

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

Expected :

  • 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?

like image 848
niksvp Avatar asked Jan 20 '11 09:01

niksvp


1 Answers

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);
like image 113
Tim Pietzcker Avatar answered Sep 25 '22 20:09

Tim Pietzcker