Reputation: 111
Why is my regex pattern only returning the name/value of the first test ? I thought .+ would make it a non greedy pattern.
This is my code
$value = "Starting test: Connectivity
Starting test: CheckSecurityError
Starting test: DFSREvent"
$value -match 'Starting test: (?<testName>.+)'
$matches.testName
This is my output
True
Connectivity
Upvotes: 0
Views: 1729
Reputation: 24430
One approach would be to use the .Net class, 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}
Output
Connectivity
CheckSecurityError
DFSREvent
Or you can use Select-String
as mentioned in other answers / only using %{$_.Groups['testName'].value
to pull back the relevant capture groups' values from your matches.
$value |
select-string -Pattern 'Starting test: (?<testName>.+)' -AllMatches |
% Matches |
%{$_.Groups['testName'].value}
Upvotes: 1
Reputation:
$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}
Sample output:
Connectivity
CheckSecurityError
DFSREvent
-----------------
Connectivity
CheckSecurityError
DFSREvent
Upvotes: 1
Reputation: 9036
You should use select-string
:
$value -split '\n' | sls 'Starting test: (?<testName>.+)' | % { Write-Host 'Result' $_ }
Upvotes: 0