Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1072
  • Last Modified:

Named group regular expressions in Powershell

In powershell I am trying to search a file specified by the $mypath variable for a given regular expression pattern $mypattern. The regular expression uses named groups of the form '(?<age>[0-9]*Years)'. How can I get the named group value into a variable that I can use. I have tried the following as a guess but havent got anywhere.

$result = select-string -path $mypath -pattern $mypattern | foreach-object {$_.matches} | foreach-object {$_.groups['age']} | select-object value

Open in new window

0
Blowfelt82
Asked:
Blowfelt82
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
try:

select-string -path $mypath -pattern $mypattern | select -expand Matches | foreach {$_.groups["age"].value}

Open in new window

0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Select-String seems to ignore named captures. The groups are always named like the captured value, which makes it less useful. You will have to use the numeric index into the Groups collection to get access:
select-string -path $mypath -pattern $mypattern |
  select -Expand Matches |
  foreach-object {$_.Groups[1].Value}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Worried about phishing attacks?

90% of attacks start with a phish. It’s critical that IT admins and MSSPs have the right security in place to protect their end users from these phishing attacks. Check out our latest feature brief for tips and tricks to keep your employees off a hackers line!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now