Share via


RegEx Named Groups with Select-String

Question

Tuesday, December 8, 2009 3:11 PM | 1 vote

Dears
How can I get the named groups via select-string?
for example :
text : "aa12aa"
regex : "aa(?<digit>[\d]+)aa"

The number "12" changes by time, and the text "aa" remains no change
How to get the number "12" by select-string and regular expression?

Thank you

All replies (3)

Tuesday, December 8, 2009 6:03 PM ✅Answered | 4 votes

Tested on PowerShell 2.0:

PS >  "aa12aa" | select-string -Pattern  "aa(?<digit>[\d]+)aa" | select -expand Matches | foreach {$_.groups["digit"].value}
12

If it doesn't work in v1 try with regex:

PS > [regex]::match($text,'aa(?<digit>[\d]+)aa') | foreach {$_.groups["digit"].value}
12Shay Levy [MVP]
http://blogs.microsoft.co.il/blogs/ScriptFanatic
PowerShell Toolbar


Tuesday, December 8, 2009 6:07 PM ✅Answered | 4 votes

Yep, kind of annoying but if you want to use select-string to get named groups, you have to run the match twice.

**$patt = "aa(?<digit>[\d]+)aa"
$content = gc "textfile.txt"

# this works
$content | select-string $patt |%{$null = $_.Line -match $patt; $matches['digit'] }
# or
$content | select-string $patt |%{[regex]::match($_.Line, $patt).Groups['digit'].Value }
**
Alternate approach is to not use select-string.  This is the cleanest code, plus I think might be faster since it's only doing the match once.

**$content |?{$_ -match $patt}|%{$matches['digit']}

**Thanks,
-Lincoln


Tuesday, December 8, 2009 4:05 PM

select-string returns a -matchinfo object, which does not appear to include the captures.  You need to run a match operation against the .line string of the matchinfo objects retruned by select-string to get the captures.