1

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

TtT23
  • 6,876
  • 34
  • 103
  • 174
  • possible duplicate of [RegEx for an IP Address](http://stackoverflow.com/questions/4890789/regex-for-an-ip-address) – tripleee Sep 06 '12 at 05:17

3 Answers3

3

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);
Habib
  • 219,104
  • 29
  • 407
  • 436
2

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
Joey
  • 344,408
  • 85
  • 689
  • 683
  • 1
    Well, a *second* match will match the port, yes. But the first match in the string should always be the IP. See example above. – Joey Sep 06 '12 at 05:16
1
\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
Brad Werth
  • 17,411
  • 10
  • 63
  • 88