开发者

Accurate IP detection regex help

I need to find Internal IP addresses by us开发者_如何学编程ing 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?


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).


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


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+|$)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜