Solved

Named group regular expressions in Powershell

Posted on 2013-01-15
2
784 Views
Last Modified: 2013-01-31
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
Comment
Question by:Blowfelt82
2 Comments
 
LVL 42

Expert Comment

by:sedgwick
ID: 38778761
try:

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

Open in new window

0
 
LVL 68

Accepted Solution

by:
Qlemo earned 500 total points
ID: 38778832
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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
"Migrate" an SMTP relay receive connector to a new server using info from an old server.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now