Validating an IP with regex

后端 未结 5 1563
一整个雨季
一整个雨季 2021-01-14 01:14

I need to validate an IP range that is in format 000000000 to 255255255 without any delimiters between the 3 groups of numbers. Each of the three groups that the final IP c

相关标签:
5条回答
  • 2021-01-14 01:16

    This is a pretty common question. Here is a nice intro page on regexps, that has this case as an example. It includes the periods, but you can edit those out easily enough.

    0 讨论(0)
  • 2021-01-14 01:16
    \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b
    

    I use this RegEx for search all ip in code from my project

    0 讨论(0)
  • 2021-01-14 01:23

    I would personally not use regex for this. I think it's easier to ensure that the string consists of 9 digits, split up the string into 3 groups of 3-digit numbers, and then check that each number is between 0 and 255, inclusive.

    If you really insist on regex, then you could use something like this:

    "([0-1][0-9][0-9]|2[0-4][0-9]|25[0-5]){3}"
    

    The expression comprises an alternation of three terms: the first matches 000-199, the second 200-249, the third 250-255. The {3} requires the match exactly three times.

    0 讨论(0)
  • 2021-01-14 01:36
    ^([01]\d{2}|2[0-4]\d|25[0-5]){3}$
    

    Which breaks down in the following parts:

    1. 000-199
    2. 200-249
    3. 250-255

    If you decide you want 4 octets instead of 3, just change the last {3} to {4}. Also, you should be aware of IPv6 too.

    0 讨论(0)
  • 2021-01-14 01:43

    for match exclusively a valid IP adress use

    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}
    

    instead of

    ([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}
    

    because many regex engine match the first possibility in the OR sequence

    you can try your regex engine with : 10.48.0.200

    0 讨论(0)
提交回复
热议问题