I am doing a practice in c# and I would like to know how I can obtain a substring of a string that meets certain requirements.
For example, I would want to get out what corresponds to an IP that would be 192.168.1.1
. I had thought about regular expressions, but I don't know how to do it, since the following code doesn't return any value to me.
Regex ipV4 = new Regex(@"^\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
string s = "naieofnai555aedae192.168.1.1andaiodane";
Match match = ipV4.Match(s);
if (match.Success)
{
Console.WriteLine("IP was {0}", match.Groups[1].Value);
}
The problem is that you are using
^
and\b
in your expression and neither of the 2 is true.^
matches the beginning of the text.\b
matches a whole word boundary (this would work if there were no letters, numbers or underscores around the IP).This is explained in Delimiters .
Also, you're using
.Groups[1]
, but that's used when there are parentheses inside the regular expression (this is explained in The Captured Group ).If you really want to extract any group of 4 digits separated by dots, you just need to remove those delimiters.
Get only the first match
Demo: http://ideone.com/NUfVeL
find all matches
Demo: http://ideone.com/dR00mt
Alternatives to match an IP
It can be written more bounded (although it would not change the efficiency):
Or you could only allow numbers between 0 and 255 (to extract any IP).
Try this validation:
Testing federhico's answer with the first case did return fine, but the second did not, because the ip is not separated by spaces in the "input" text. That is, it works when "naieofnai555aedae 192.168.1.1 andaiodane". Mariano's explanation...
Based on this Question , I would tell you to try
either