Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture multiple regex matches, from a single line, into the $matches magic variable in Powershell?

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. :)

like image 946
Etzeitet Avatar asked Jun 29 '10 14:06

Etzeitet


People also ask

Can you use regex in PowerShell?

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.

What is$ 1 PowerShell?

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”.

How do you match expressions in regex?

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).

What does capture mean in regex?

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.


2 Answers

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."

like image 196
Keith Hill Avatar answered Oct 18 '22 08:10

Keith Hill


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 
like image 45
sonjz Avatar answered Oct 18 '22 07:10

sonjz