In C#, Given a string in a format like this:
http://10.242.33.210:5000
ftp://52.42.12.52:7000/
How do I utilize regex to retrieve only the IP (port should be discarded)
For the above two example, regex should match 10.242.33.210 and 52.42.12.52
In C#, Given a string in a format like this:
http://10.242.33.210:5000
ftp://52.42.12.52:7000/
How do I utilize regex to retrieve only the IP (port should be discarded)
For the above two example, regex should match 10.242.33.210 and 52.42.12.52
Instead of Regex you may create a Uri and get its Host property
Uri url = new Uri("ftp://52.42.12.52:7000/");
Console.Write(url.Host);
Pretty easy, actually:
[\d.]+
will match a run of digits and dots. In your case the IP address without the port. You can make it more complicated by trying to conform to how an IP looks like (numbers between 0 and 255, or just one to three digits between the dots) but if all you ever expect is input like above, then this should be fine.
Quick Powershell test:
PS> $tests = 'http://10.242.33.210:5000','ftp://52.42.12.52:7000/'
PS> $tests | %{ $_ -match '[\d.]+' | Out-Null; $Matches}
Name Value
---- -----
0 10.242.33.210
0 52.42.12.52
\b([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\b
The same but shorter (from zerkms):
\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b