0

I'm trying to retrieve the IP address from a string. I'm definitely not the first to ask this question, but I couldn't really find an answer doing exactly what we need.

If there is somewhere in the string a combination of xxx.xxx.xxx.xxx, regardless of the text around it, it should extract this number with the dots in between. So it can be used with Test-Connection.

I'm not trying to determin if an IP Address is valid, but I am trying to retrieve the IP Address from a string. Even if it is invalid, like say 900.999.800.254.

Example:

Input             Expected result
-----             ---------------
IP_10.57.50.91    10.57.50.91
10.57.50.73       10.57.50.73
10.58.4.37 IP     10.58.4.37
ip 10.63.1.22     10.63.1.22
BELPRLIXH300      $False
ip 10.63          $False

I've tried so far the the regex's suggested here but they don't give us the IP address as output in the variable $Matches.

DarkLite1
  • 13,637
  • 40
  • 117
  • 214
  • Thank you for the suggestion, but if I try `'IP_10.10.22.45' -match "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"` it doesn't work and gives me `$False` instead of the number. – DarkLite1 Jul 02 '15 at 07:46
  • I successfully testet every IP address with the ExtractValidIpAddress function from you link. – Martin Brandl Jul 02 '15 at 07:48
  • Yes, it does give `$True` or `$False`, but it doesn't extract the number to be used with `Test-Connection`. – DarkLite1 Jul 02 '15 at 07:50
  • remove the anchors... ^,$ – Avinash Raj Jul 02 '15 at 07:51
  • If I try this `'IP_10.10.22.45' -match "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"` it doesn't give the correct output, not even in `$Matches`. – DarkLite1 Jul 02 '15 at 07:52
  • check this https://regex101.com/r/rS5mE7/1 – Avinash Raj Jul 02 '15 at 07:54

1 Answers1

6
$ips = @('IP_10.57.50.91',
    '10.57.50.73',
    '10.58.4.37 IP',
    'ip 10.63.1.22',
    'BELPRLIXH300',
    'ip 10.63'
)

$regex = [regex] "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

$regex.Matches($ips) | %{ $_.value }
David Brabant
  • 41,623
  • 16
  • 83
  • 111