Patan
Patan

Reputation: 17873

Regex to match Ipv4 with mask

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

Answers (3)

Ciabaros
Ciabaros

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:

  • 0.0.0.0/0
  • 255.255.255.255/32
  • 100.70.60.50 (This version supports no mask)

Rejected examples:

  • 001.01.01.01/09 (matched by currently accepted answer)
  • 256.0.0.0/30 (256 is out of range!)
  • 100.70.60.50/33 (33 is out of bounds)
  • 100.70.60.50/ (incomplete mask)

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

Toto
Toto

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

Henrik Gering
Henrik Gering

Reputation: 1871

In your example, if you want it to match both adresses, remove beginning ^ and trailing $

Upvotes: 0

Related Questions