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.
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.
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.
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.
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}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With