Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex PCRE2 verify range of ip address

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]?)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading