Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting matches using regex and then passing them into an array

Tags:

powershell

 $htmltitle1 = "{Quit|Discontinue|Stop|Cease|Give Up} Tottenham Manager {HEY}"
  $reg = "\{.*?\}"
  $found = $htmltitle1 -match $reg

  $spuntext = @()
  If ($found)
    {    
         ([regex]$reg).matches($htmltitle1)  
    }

I can see the $matches (below) but how would I extract each match into the $spuntext array? Lol I've been banging my head with this for hours trying different things.

Groups   : {{Quit|Discontinue|Stop|Cease|Give Up}}
Success  : True
Captures : {{Quit|Discontinue|Stop|Cease|Give Up}}
Index    : 0
Length   : 37
Value    : {Quit|Discontinue|Stop|Cease|Give Up}

Groups   : {{HEY}}
Success  : True
Captures : {{HEY}}
Index    : 56
Length   : 5
Value    : {HEY}

Key   : 0
Value : {Quit|Discontinue|Stop|Cease|Give Up}
Name  : 0
like image 588
Kino Avatar asked Jun 27 '13 21:06

Kino


1 Answers

Like this:

$htmltitle1 = "{Quit|Discontinue|Stop|Cease|Give Up} Tottenham Manager {HEY}"
$reg = '{.*?}'
$spuntext = $htmltitle1 | Select-String $reg -AllMatches |
            ForEach-Object { $_.Matches.Value }

Result:

PS C:\> $spuntext
{Quit|Discontinue|Stop|Cease|Give Up}
{HEY}

Edit: Microsoft simplified property access in PowerShell v3. To make it work in PowerShell v2 you have to split ForEach-Object { $_.Matches.Value } into 2 separate loops:

$spuntext = $htmltitle1 | Select-String $reg -AllMatches |
            ForEach-Object { $_.Matches } |
            ForEach-Object { $_.Value }

or expand the properties:

$spuntext = $htmltitle1 | Select-String $reg -AllMatches |
            Select-Object -Expand Matches |
            Select-Object -Expand Value
like image 83
Ansgar Wiechers Avatar answered Oct 14 '22 00:10

Ansgar Wiechers