dereli
dereli

Reputation: 1864

Accurate IP detection regex help

I need to find Internal IP addresses by using a regex, I've managed to do it, but in the following cases all 4 is matching. I need a regex which doesn't match the first but matches the following 3. Each line is a different input.

! "version 10.2.0.4.0 detected"
+ "version 10.2.0.42 detected"
+ "version 10.2.0.4 detected"
+ "version 10.2.0.4"

edit: my current regex is

(?-i)\b10\.2.(?:[0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b

Any ideas?

Upvotes: 1

Views: 208

Answers (3)

dr. evil
dr. evil

Reputation: 27275

I think @wrikken's answer was correct but it was in the comments of one of the deleted posts:

Here it is:

(?<![0-9]\.)((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?!\.[0-9])

Upvotes: 1

bdukes
bdukes

Reputation: 156035

Use whichever regex that you want to match the IP (either of the above two work for your scenarios), and use (?:^|\s+) at the beginning and (?:\s+|$) at the end to make sure that there's whitespace or nothing around the value.

  • (?:) defines a group that doesn't capture its contents
  • ^ is the beginning of a line/string and $ is the end of a line\string
  • \s+ is one or more whitespace characters
  • | is the alternation operator, i.e. one or the other option on either side of the |

Using your expression as a starting point, you end up with

(?-i)(?:^|\s+)10\.2.(?:[0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\s+|$)

Upvotes: 0

polemon
polemon

Reputation: 4782

In PCRE:

/\b((1?[1-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))(\.((1?[1-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))){3}\b/

This is a rather strict match, not allowing multiple zeros, so 00.00.00.00 is invalid (0.0.0.0 is).

Upvotes: 2

Related Questions