0

Currently I'm working on a regular expression wrote in PCRE2 to check a range of IP address

^(10\.).+|(172\.16).+|(192\.168).+

I need the regular expression to check also if in the string I can find any ip between 172.16.X.X - 172.31.X.X

The current regex it's working but not checking this range specifically ... it's capturing everything that's 172.16.X.X

I tried ^(10\.).+|(172\.[16-31]).+|(192\.168).+ but It doesn't work in this way.

Also I'm using https://regex101.com/ to debug this expression ... is it a good way to check if it's right?

  • Like this? `\b172\.(?:1[789]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b` https://regex101.com/r/04KJxW/1 – The fourth bird May 27 '22 at 15:05
  • @Thefourthbird https://regex101.com/r/2q8nF1/1 this new one isn't capturing the other specification ... can you see? Should I substitute the whole capturing group to this whole expression? – Daniel Lima Fortes May 27 '22 at 15:08
  • 1
    Frame challenge: have you considered using a library that can validate based on an address range in CIDR notation, instead of building a regular expression? – IMSoP May 27 '22 at 15:12
  • @DanielLimaFortes Like this then? https://regex101.com/r/mURVCf/1 – The fourth bird May 27 '22 at 15:13
  • @IMSoP this case works specifically with regex ... I'd be glad if was using any library – Daniel Lima Fortes May 27 '22 at 15:14
  • 1
    @Thefourthbird it's perfect!! but I miss spelled the range writting it as 172.17.x.x - 172.31.x.x instead of 172.16.x.x - 172.31.x.x (I edited the question) – Daniel Lima Fortes May 27 '22 at 15:20
  • Regular expressions are overkill when you can just use [`ip2long()`](https://www.php.net/manual/en/function.ip2long), math, and bitwise/comparison operators. https://www.ccexpert.us/routing-switching/subnetting-math.html – Sammitch May 27 '22 at 17:44

1 Answers1

3

You can use

\b(?:(?:192\.168|172(?:\.(?:1[6-9]|2\d|3[01])))(?:\.\d{1,3}){2}|10(?:\.\d{1,3}){3})\b
  • \b A word boudnary to prevent a partial word match
  • (?: Non capture group
    • (?: Non capture group
      • 192\.168 Match 192.168
      • | Or
      • 172(?:\.(?:1[6-9]|2\d|3[01])) Match 172. and then 16 till 31
    • ) Close non capture gorup
    • (?:\.\d{1,3}){2} Match 2 times . and 1-3 digits
    • | Or
    • 10(?:\.\d{1,3}){3} Match 10 and 3 times . and 1-3 digits
  • ) Close non capture group
  • \b A word boundary

Regex demo

If you want to make the \d{1,3} digits more specific, then you can also use:

(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

The fourth bird
  • 154,723
  • 16
  • 55
  • 70