Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the IP of the string using RegEx

Tags:

string

c#

regex

ip

How to extract the IP of the string below using RegEx?

... sid [1544764] srv [CFT256] remip [10.0.128.31] fwf []...

I tried the code below but did not return the expected value:

string pattern = @"remip\ \[.\]";
MatchCollection mc = Regex.Matches(stringToSearch, pattern );


Thanks in advance.

like image 544
lsalamon Avatar asked May 09 '12 15:05

lsalamon


People also ask

How to write regex for a whole IP address?

If we can write regular expression for X, then we can easily write regex for whole ip address as this x is repeating four times with a dot as seperator. When you are writing regex for a number, you have to keep in mind that regex does not know numbers but takes them as string characters.

How to extract an IP address from a string?

The easiest way is just to take any string of four decimal numbers separated by periods is In the following example we simply extracting an IP address from a given string. But, the above example also accepts the wrong IP address like 596.368.258.269.

What is Perl and how to extract an IP address?

Perl stands for Practical Extraction and Reporting Language and this not authorized acronym. One of the most powerful features of the Perl programming language is Regular Expression and in this article, you will learn how to extract an IP address from a string.

Which regular expression pattern represents IPv4 host address?

A regular expression pattern that represents IPv4 Host Address is: [0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}


1 Answers

Try this:

@"remip \[(\d+\.\d+\.\d+\.\d+)\]"

To clarify... the reason yours doesn't work is because you are only matching . inside the [ and ]. A single . matches only a single character. You could add a * (zero or more) or a + (one or more) to make it work. In addition, surrounding it with parenthesis: ( and ), means you can extract just the IP address directly from the second item in the MatchCollection.

like image 199
Jon Grant Avatar answered Sep 30 '22 19:09

Jon Grant