一種方法將是使用.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}
如果它像其他正則表達式引擎一樣,除非您告訴它,否則點不匹配換行符。同樣,您擁有它的方式,捕獲組將包括第二秒「開始測試:」字符串以及所有空白字符。 –
你想讓它完全返回嗎? – Matt
[如何捕獲多個正則表達式匹配,從單一行到Powershell中的$ matches魔術變量?](https://stackoverflow.com/questions/3141851/how-to-capture-multiple-regex-匹配從單線進入匹配mag) – TessellatingHeckler