SwiftD
SwiftD

Reputation: 11

RegEx for IP Address with no range limit

I'm looking for a regex that finds IP Addresses with no range limit (i.e. 0-999). This is "simpler" than a regular IP Address regex but I'm learning regex and am stumped on how to essentially end the regex and not match IP Addresses with more than 4 periods or characters before/after it.

This is what I have: "/\b(\d{1,3}\.){3}(\d{1,3})\b/"

So, with this regex it will find most IP Addresses but will fail when there is an IP Address like this:

1.2.3.4.5

Appreciate the help. And it doesn't matter what flavor or regex, just need to know how to not match the case above.

Upvotes: 1

Views: 195

Answers (2)

Senthil
Senthil

Reputation: 55

You can use this one also.

^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627341

You may use lookarounds to restrict the context around your expected matches:

\b(?<!\d\.)(?:\d{1,3}\.){3}\d{1,3}\b(?!\.\d)
  ^^^^^^^^^                         ^^^^^^^^

See the regex demo

Here,

  • (?<!\d\.) is a negative lookbehind that fails the match if, immediately to the left of the current location, there is a digit + .
  • (?!\.\d) is a negative lookahead that fails the match if, immediately to the right of the current location, there is a . + a digit.

To also make sure the octets of 1 to 3 digits are matched, you may add more restriction:

\b(?<!\d\.|\d)(?:\d{1,3}\.){3}\d{1,3}\b(?!\.?\d)
  ^^^^^^^^^^^^                         ^^^^^^^^^

See another regex demo.

Here, (?<!\d\.|\d) also fails if there is a digit immediately in front of the current location, and the lookahead is also failing when there is a digit without a dot in front after the expected match.

Upvotes: 2

Related Questions