Let's say I have the string "blah blah F12 blah blah F32 blah blah blah" and I want to match the F12 and F32, how would I go about capturing both to the Powershell magic variable $matches?
If I run the following code in Powershell:
$string = "blah blah F12 blah blah F32 blah blah blah" $string -match "F\d\d"
The $matches variable only contains F12
I also tried:
$string -match "(F\d\d)"
This time $matches had two items, but both are F12
I would like $matches to contain both F12 and F32 for further processing. I just can't seem to find a way to do it.
All help would be greatly appreciated. :)
Powershell: The many ways to use regex The regex language is a powerful shorthand for describing patterns. Powershell makes use of regular expressions in several ways. Sometimes it is easy to forget that these commands are using regex becuase it is so tightly integrated.
Replacement Text as a Literal String $& is the overall regex match, $1 is the text matched by the first capturing group, and ${name} is the text matched by the named group “name”.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
capturing in regexps means indicating that you're interested not only in matching (which is finding strings of characters that match your regular expression), but you're also interested in using specific parts of the matched string later on.
You can do this using Select-String in PowerShell 2.0 like so:
Select-String F\d\d -input $string -AllMatches | Foreach {$_.matches}
A while back I had asked for a -matchall
operator on MS Connect and this suggestion was closed as fixed with this comment:
"This is fixed with -allmatches parameter for select-string."
I suggest using this syntax as makes it easier to handle your array of matches:
$string = "blah blah F12 blah blah F32 blah blah blah" ; $matches = ([regex]'F\d\d').Matches($string); $matches[1].Value; # get matching value for second occurance, F32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With