The problem is that you are using ^
and \b
in your expression and none of the 2 is fulfilled.
-
^
matches the start of the text.
-
\b
matches a full word limit (this would work if there were no letters, numbers or underscores around the IP).
This is explained in Delimiters .
Also, you are using .Groups[1]
, but that is used when there are parentheses within the regular expression (this is explained in The captured group ).
If you really want to extract any group of 4 digits separated by periods, you only need to delete those delimiters.
Get only the first match
using System.Text.RegularExpressions;
string ipv4 = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
string s = @"naieofnai555aedae192.168.1.1andaiodane";
Match m = Regex.Match(s, ipv4);
if (m.Success)
{
Console.WriteLine("IP encontrado: {0}", m.Value);
}
Demo: link
Find all matches
using System.Text.RegularExpressions;
string ipv4 = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
string s = @"naieofnai555aedae192.168.1.1andaiodane111.222.111.222ooooo";
foreach (Match m in Regex.Matches(s, ipv4)) //bucle para obtener todas las coincidencias
{
Console.WriteLine("IP encontrado: {0}", m.Value);
}
Demo: link
Alternatives to match an IP
You can write more limited (although it would not change the efficiency):
string ipv4 = @"\d{1,3}(?:\.\d{1,3}){3}";
Or you could only allow numbers between 0 and 255 (to extract any IP).
string ipv4 = @"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}";