1

Ok, long time visitor, first time post.

Instead of PowerShell telling me the result of my Regular Expression is "True" or "False", instead I would like the string. I know there are other ways to do this and I already have a working version, but I would like to use Regular Expressions to "extract" the string.

For example:

$ipconfig = ipconfig | select-string "IPv4" | select-object -first 1
$ipconfig -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"

Just returns "True", instead I would like the IP address.

Is there a way of accomplishing this using regex?

Thanks!

2 Answers 2

9

You've already got it, just need to check a variable you get for free:

$ipconfig = ipconfig | select-string "IPv4" | select-object -first 1
if ($ipconfig -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b") { 
    $matches[0]
}

Alternatively, you can use the .NET object:

$ipconfig = ipconfig | select-string "IPv4" | select-object -first 1
([regex]"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b").matches($ipconfig) | % { $_.value }

Enjoy :)

Sign up to request clarification or add additional context in comments.

Comments

1

Using -replace:

 $ipconfig = ipconfig | select-string "IPv4" | select-object -first 1 
 $ipconfig -replace '.*\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b.*','$1' 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.