phpregexip-addresspcrepcre2

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

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
    

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