使用正则表达式提取匹配项,然后将它们传递给数组

时间:2013-06-27 21:14:41

标签: powershell

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

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

我可以看到$ matches(下面)但是如何将每个匹配提取到$ spuntext数组中?大声笑我几个小时都在尝试不同的东西。

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

2 个答案:

答案 0 :(得分:6)

像这样:

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

结果:

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

编辑:PowerShell v3中的Microsoft简化了属性访问。要使其在PowerShell v2中运行,您必须将ForEach-Object { $_.Matches.Value }分成两个独立的循环:

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

或展开属性:

$spuntext = $htmltitle1 | Select-String $reg -AllMatches |
            Select-Object -Expand Matches |
            Select-Object -Expand Value

答案 1 :(得分:0)

在今天搞砸了语法之后,还想出了这个问题,以防它像其他任何像我这样混淆的新手:(在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 
相关问题