Reputation: 17873
I am validating a Ipv4 address by a regex and it does not support subnet mask.
^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$
Can some one help me with the regex which supports mask as well.
Here is a working example of this regex: demo
Upvotes: 2
Views: 12406
Reputation: 2159
Here's a proper IPv4 subnet regex without any lookaheads that matches correct notation.
Mask OPTIONAL Version:
^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/(3[0-2]|[1-2]?\d))?$
Matched examples:
Rejected examples:
Mask REQUIRED Version: If you'd like a version that requires the mask, then use this instead:
^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\/(3[0-2]|[1-2]?\d)$
Upvotes: 1
Reputation: 91385
Add (?:/[0-2]\d|/3[0-2])?
at the end of your regex. You can also simplify the regex:
^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.(?:[01]?\d\d?|2[0-4]\d|25[0-5])){3}(?:/[0-2]\d|/3[0-2])?$
Upvotes: 7
Reputation: 1871
In your example, if you want it to match both adresses, remove beginning ^ and trailing $
Upvotes: 0