2017-06-29 102 views
0

爲什麼我的正則表達式模式只返回第一個測試的名稱/值?我認爲,+會使它成爲一種非貪婪的模式。Powershell正則表達式只返回第一個結果

這是我的代碼

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


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

$matches.testName 

這是我的輸出

True 
Connectivity 
+1

如果它像其他正則表達式引擎一樣,除非您告訴它,否則點不匹配換行符。同樣,您擁有它的方式,捕獲組將包括第二秒「開始測試:」字符串以及所有空白字符。 –

+0

你想讓它完全返回嗎? – Matt

+0

[如何捕獲多個正則表達式匹配,從單一行到Powershell中的$ matches魔術變量?](https://stackoverflow.com/questions/3141851/how-to-capture-multiple-regex-匹配從單線進入匹配mag) – TessellatingHeckler

回答

0

你應該使用select-string

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

我將如何做到這一點作爲一個多行的正則表達式? – KingBain

+0

在'select-string'調用中添加'-AllMatches'參數。在正則表達式定義中,不嚴格地使用'multi-line'(即改變'^'和'$'的行爲,但這意味着它能夠返回多個匹配,我認爲這就是你所追求的。全局修改器已應用(https://www.w3schools.com/jsref/jsref_regexp_g.asp) – JohnLBevan

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

一種方法將是使用.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}