Home > OS >  How do I specify a regex in Java to match any IP address that does not end in ".0.0"?
How do I specify a regex in Java to match any IP address that does not end in ".0.0"?

Time:08-19

I need to validate that a String field (representing an IP address) in an object does not end in .0.0. I will be using the @Pattern annotation to perform the validation.

I tried the following:

@Pattern(regexp="(?!(\\.0\\.0$))", message="IP address must not end in .0.0")
private String ipAddress;

This correctly printed out the validation error message for 192.168.0.0. However, it incorrectly printed out the validation error message for valid IP addresses like 192.168.0.1 and 192.168.1.0.

What regex pattern would achieve what I want?

CodePudding user response:

I found a tutorial on negative look ahead that seems to do what you want:

REGEX: \d \.\d \.(?!0\.0)\d \.\d 

You'll have to add extra slashes for a Java string. (I tested this on an old "REGEX Tester" program I made in 2016 or so, no code was harmed in the making of that regex.)

The short explanation is the "negative look ahead" is used to invalidate a string of "0.0". The regex finds the first two digit strings (\d \.\d \.) then "looks ahead" without updating the current position for the string "0.0" (?!0\.0). If it finds that string, then it invalidates the match, because it's negative look ahead, which only matches if it doesn't find the string. If it doesn't find the string then we just go on to match the final two octets as normal.

I think there's several ways for this to go wrong however and I think I'd recommend a full IP address parser (what about IPV6 addresses?) and then testing the octets/16-bit numbers as numbers, not strings.

The website: https://regexland.com/regex-match-all-except/

  • Related