tags:

views:

43

answers:

3

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?

A: 

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+|$)
bdukes
Don't forget the quote for the last one.
Billy ONeal
I was assuming that was denoting the end of the string, rather than a literal quote...
bdukes
thanks, but what i need was "(?!\.[0-9])" at the end before "\b"
dereli
+2  A: 

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

polemon
+1 for a more complete answer -- it should work in .net (as required by the question) if you remove the leading and trailing slashes.
Billy ONeal
Well the slashes are part of PCRE, I always use PCRE when showing Regex.
polemon
@polemon: Yes, but the question explicitly states .NET is the engine he is using.
Billy ONeal
This one will also match the 10.2.0.4 part of the first example...
bdukes
@bdukes: no it won't, the `\b` takes care of that.
polemon
Sorry, my comments was incorrect, this doesn't help. The correct answer was from Wrikken's comment. Sorry for the misunderstanding.
dereli
The `\b` matches the "." after 10.2.0.4 (in .NET, if not other engines...)
bdukes
+1  A: 

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])
dr. evil
The important point is (?!\.[0-9]) at the end.
dereli