ca9163d9
ca9163d9

Reputation: 29179

Powershell capture multiple values?

The following code returns only one match.

$s = 'x.a,
x.b,
x.c
'
$s -match 'x\.(.*?)[,$]'
$Matches.Count # return 2
$Matches[1] # returns a only

Excepted to return a, b, c.

Upvotes: 2

Views: 144

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

The -match operator only finds the first match. The -AllMatches with Select-String will fetch all matches in the input. Also, [,$] matches a , or $ literal chars, the $ is not a string/line end metacharacter.

A possible solution may look like

 Select-String 'x\.([^,]+)' -input $s -AllMatches | Foreach {$_.Matches} | Foreach-Object {$_.Groups[1].Value}

The pattern is x\.([^,]+), it matches x. and then captures into Group 1 any one or more chars other than ,.

Upvotes: 2

Related Questions