0
0
PowerShellscripting~5 mins

Named captures in PowerShell

Choose your learning style9 modes available
Introduction
Named captures let you find parts of text and give each part a name. This makes it easy to get the exact piece you want without guessing positions.
You want to extract a date from a text and get the year, month, and day separately.
You need to find a person's name and phone number from a message and keep them labeled.
You want to check a log file and pull out error codes with their descriptions.
You are parsing a URL and want to get the protocol, domain, and path clearly.
You want to split a full name into first and last names from a string.
Syntax
PowerShell
'(?<name>pattern)'
Use inside parentheses to name a capture group.
You can access named groups by their name after matching.
Examples
Extract year, month, and day from a date string using named captures.
PowerShell
$text = 'Date: 2024-06-15'
if ($text -match '(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})') {
  $matches['year']
  $matches['month']
  $matches['day']
}
Capture first and last names separately from a full name.
PowerShell
$text = 'Name: John Doe'
if ($text -match 'Name: (?<first>\w+) (?<last>\w+)') {
  "$($matches['first']) $($matches['last'])"
}
Sample Program
This script finds the username and email from a string using named captures and prints them clearly.
PowerShell
$text = 'User: alice, Email: alice@example.com'
if ($text -match 'User: (?<username>\w+), Email: (?<email>\S+)') {
  Write-Output "Username: $($matches['username'])"
  Write-Output "Email: $($matches['email'])"
} else {
  Write-Output 'No match found.'
}
OutputSuccess
Important Notes
Named captures make your code easier to read and maintain.
The $matches automatic variable holds all named groups after a successful match.
If the pattern does not match, $matches will not contain the named groups.
Summary
Named captures label parts of a matched text for easy access.
Use the syntax (?<name>pattern) inside your regex.
Access captured parts by name using $matches['name'] in PowerShell.