Powershell Regex只返回第一个结果

时间:2017-06-29 15:11:08

标签: regex powershell

为什么我的正则表达式只返回第一个测试的名称/值?我想。+会使它成为一种非贪婪的模式。

这是我的代码

$value = "Starting test: Connectivity
          Starting test: CheckSecurityError
          Starting test: DFSREvent"


$value -match 'Starting test: (?<testName>.+)' 

$matches.testName

这是我的输出

True
Connectivity

3 个答案:

答案 0 :(得分:1)

$value = @"
Starting test: Connectivity
Starting test: CheckSecurityError
Starting test: DFSREvent
"@

$Pattern = '^\s*Starting test: (?<testName>.+?)$'
($value -split '\n')|
    Where-Object {$_ -match $Pattern }|
      ForEach{$matches.testname}

"-----------------"
## alternative without named capture group

$value -split '\n' | 
  select-string -pattern  'Starting test: (.+)' -all | 
    ForEach {$_.matches.groups[1].value}

示例输出:

Connectivity
CheckSecurityError
DFSREvent
-----------------
Connectivity
CheckSecurityError
DFSREvent

答案 1 :(得分:1)

一种方法是使用.Net类System.Text.RegularExpressions.Regex

$value = "Starting test: Connectivity
          Starting test: CheckSecurityError
          Starting test: DFSREvent"
$regex = [System.Text.RegularExpressions.Regex]::new('Starting test: (?<testName>.+)')
$regex.Matches($value) | %{$_.Groups['testName'].value}

#or by calling the static method rather than instantiating a regex object:
#[System.Text.RegularExpressions.Regex]::Matches($value, 'Starting test: (?<testName>.+)') | %{$_.Groups['testName'].value}

<强>输出

Connectivity
CheckSecurityError
DFSREvent

或者您可以使用其他答案中提到的Select-String /仅使用%{$_.Groups['testName'].value从匹配中提取相关的捕获组值。

$value | 
    select-string -Pattern 'Starting test: (?<testName>.+)' -AllMatches | 
    % Matches | 
    %{$_.Groups['testName'].value} 

答案 2 :(得分:0)

您应该使用select-string

$value -split '\n' | sls 'Starting test: (?<testName>.+)' | % { Write-Host 'Result' $_ }