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

51,178

Solution 1

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

Solution 2

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

Solution 3

I see 2 scenarios that are handled differently:

  1. extracting all matches of a single pattern
  2. extracting single match of multiple patterns

1. extract all matches of one pattern: select-string + -allmatches

  • e.g. regex: (?<=jobs).*
  • counter-intuitive but you need to use Select-String to handle this like I am to get ids of nomad jobs from the output exemplified below
$m = "Watch the deployment in realtime at: https://nomad.foo.net/ui/jobs/20e183af-8243-11eb-a2af-0a58a9feac2a
08:23
Watch the deployment in realtime at: https://nomad.foo.net/ui/jobs/20e130e9-8243-11eb-a2af-0a58a9feac2a"
$r = "(?<=jobs/).*"
$l = Select-String $r -InputObject $m -AllMatches | 
    Foreach {$_.matches.Value}
20e183af-8243-11eb-a2af-0a58a9feac2a
20e130e9-8243-11eb-a2af-0a58a9feac2a
$l[0]
>>> 20e183af-8243-11eb-a2af-0a58a9feac2a

2. extract a single/first match of one/multiple patterns: capture groups and $Match[]

▶ $s = "Hello World from Mr Pavol"
▶ $r = "(World).*(Pavol)"
▶ $s -match $r
True
▶ $Matches
Name                           Value
----                           -----
2                              Pavol
1                              World
0                              World from Mr Pavol
Share:
51,178
Etzeitet
Author by

Etzeitet

Updated on March 24, 2021

Comments

  • Etzeitet
    Etzeitet over 3 years

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