Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for an IP Address

Tags:

c#

.net

regex

I try to extract the value (IP Address) of the wan_ip with this sourcecode: Whats wrong?! I´m sure that the RegEx pattern is correct.

String input = @"var product_pic_fn=;var firmware_ver='20.02.024';var wan_ip='92.75.120.206';if (parent.location.href != window.location.href)"; Regex ip = new Regex(@"[\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"); string[] result = ip.Split(input);  foreach (string bla in result)   {   Console.WriteLine(bla);                 }  Console.Read(); 
like image 615
h0scHberT Avatar asked Feb 03 '11 19:02

h0scHberT


People also ask

How do you represent an IP address in regex?

\d{1,3}\b will match any IP address just fine. But will also match 999.999. 999.999 as if it were a valid IP address. If your regex flavor supports Unicode, it may even match ١٢٣.

Which regex pattern can be used to find IP address?

Approach: Regex (Regular Expression) In C++ will be used to check the IP address. Specifying a range of characters or literals is one of the simplest criteria used in a regex.

How do I grep a specific IP address?

Now if you want to search for lines containing IP addresses, you'll need to use some regular expressions. An IP address is basically a dot separated sequence of 4 numbers each having 1 to 3 digits. So we can represent it this way: grep '[0-9]\{1,3\}\.


2 Answers

The [ shouldn't be at the start of your pattern. Also, you probably want to use Matches(...).

Try:

String input = @"var product_pic_fn=;var firmware_ver='20.02.024';var wan_ip='92.75.120.206';if (parent.location.href != window.location.href)"; Regex ip = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"); MatchCollection result = ip.Matches(input); Console.WriteLine(result[0]);  
like image 169
Bart Kiers Avatar answered Oct 01 '22 09:10

Bart Kiers


Very old post, you should use the accepted solution, but consider using the right RegEx for an IPV4 adress :

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

If you want to avoid special caracters after or before you can use :

^((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]?)$ 
like image 25
JPBlanc Avatar answered Oct 01 '22 11:10

JPBlanc