Kino
Kino

Reputation: 95

Extracting matches using regex and then passing them into an array

 $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

Upvotes: 7

Views: 16212

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

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

Upvotes: 11

Kino
Kino

Reputation: 95

also came up with this after messing around today trying to pick up the syntax in case it helps any other newcomers who were confused like me: (works in v2)

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

If ($found)
  {    
      [regex]::matches($htmltitle1, $reg) | % {$spuntext += $_.Value}

  }



$spuntext 

Upvotes: 1

Related Questions