Reputation: 2812
I seam to be having the hardest times with this simple regex in powershell. I want to capture the (\d+)
group of this simple match expression :
$myvar = ([regex]'<element attr="(\d+)">').Matches('<element attr="1">')
The problem is that $myvar[1]
is not defined no matter what I try.
When I run this regex in sublime text replace tool it captures the group correctly.
What am doing wrong in this simple script ?
Upvotes: 2
Views: 3140
Reputation: 200523
Unless you want to use callbacks in a replacement I'd recommend using Select-String
or the -match
operator instead of a regex
object.
PS> $m = '<element attr="1">' | Select-String '<element attr="(\d+)">'
PS> $m.Matches[0].Groups[1].Value
1
PS> '<element attr="1">' -match '<element attr="(\d+)">'
True
PS> $matches[1]
1
Upvotes: 3
Reputation: 47872
$myvar
is a collection of Match objects. There's only one match, so $myvar[0]
is the first Match object.
From there you can access .Captures
or .Groups
to get your capture group.
It would be $myvar[0].Captures[0].Value
or $myvar[0].Groups[1].Value
, depending on how you want to refer to it.
Upvotes: 3