I have a regex for IP address validation, but I need a regex for prefix validation, where the expected form is “IP Address/Prefix”.
The conditions are:
-
The prefix value should not be greater than 128
-
The prefix value should be divisible by 4.
Could anyone please help me to create a regex for prefix validation?
AFAIK you can’t do calculations using regex (e.g. number % 4 == 0 ?). Thus you’d have to use a pattern that gets all possible string combinations.
Try that one:
\b[048]\b|\b[13579][26]\b|\b[2468][048]\b|\b1[02][048]\b|\b11[26]\b\b[048]\bmatches 0, 4 and 8\b[13579][26]\bmatches 12, 16, 32, 26 etc.\b[2468][048]\bmatches 20, 24, 28, 40, 44, 48 etc.\b1[02][048]\bmatches 100, 104, 108, 120, 124, 128\b11[26]\bmatches 112 and 116Note the
\bwhich defines the whole word (in your case the prefix/suffix) must match the pattern. Without it, 136 might match[13579][26], for example.Edit: to allow leading zeros change the pattern to:
\b0{0,2}[048]\b|\b0?[13579][26]\b|\b0?[2468][048]\b|\b1[02][048]\b|\b11[26]\b(note that0{0,2}could also be written as0?0?).Edit 2: you might get rid of the
\bif you split the ip address and only have a string containing the prefix/suffix. If you then callmatches(...)you should be fine without the\b.Pattern for
matches(...)calls (no\b, allows leading zeros):0{0,2}[048]|0?[13579][26]|0?[2468][048]|1[02][048]|11[26]