0
0
PowerShellscripting~5 mins

Named captures in PowerShell - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a named capture in PowerShell regex?
A named capture lets you give a name to a part of a regular expression. This makes it easier to find and use that part later in your script.
Click to reveal answer
beginner
How do you define a named capture group in PowerShell regex?
Use the syntax (?<name>pattern) where name is the name you choose and pattern is the regex part you want to capture.
Click to reveal answer
beginner
How do you access a named capture group after a match in PowerShell?
After matching, use $matches['name'] to get the text captured by the named group called name.
Click to reveal answer
intermediate
Why use named captures instead of numbered groups?
Named captures make your code easier to read and understand because you use meaningful names instead of numbers like $matches[1].
Click to reveal answer
beginner
Example: What does this regex do? 'Name: (?<name>\w+), Age: (?<age>\d+)'
It captures a word after 'Name: ' as name and digits after 'Age: ' as age. You can then get these values by $matches['name'] and $matches['age'].
Click to reveal answer
How do you write a named capture group for a word called 'city' in PowerShell regex?
A(?<city>\w+)
B(city>\w+)
C(?city<\w+)
D(?\w+<city>)
After matching with named captures, how do you get the captured value for 'age'?
A$matches->age
B$matches.age
C$matches[age]
D$matches['age']
Why are named captures helpful in scripts?
AThey make code easier to read and maintain.
BThey run faster than numbered groups.
CThey automatically fix regex errors.
DThey prevent all script errors.
Which of these is NOT a valid way to define a named capture in PowerShell regex?
A(?<year>\d{4})
B(?P<year>\d{4})
C(?<year>\d+)
D(?<year>\d{2,4})
What will $matches['name'] contain after matching 'Name: John' with 'Name: (?<name>\w+)'?
AName
B\w+
CJohn
Dnull
Explain how to create and use named captures in PowerShell regex with an example.
Think about the pattern ( ?<name>pattern ) and accessing $matches['name']
You got /3 concepts.
    Why might named captures improve your PowerShell scripts compared to using numbered groups?
    Consider how meaningful names help you and others understand the code
    You got /3 concepts.