6
 $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
4

2 回答 2

9

像这样:

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

结果:

PS C:\> $spuntext
{退出|停止|停止|停止|放弃}
{嘿}

编辑: Microsoft 在 PowerShell v3 中简化了属性访问。要使其在 PowerShell v2 中工作,您必须拆分ForEach-Object { $_.Matches.Value }为 2 个单独的循环:

$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
于 2013-06-27T21:27:27.740 回答
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 
于 2013-06-28T20:46:20.793 回答