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.
'(?<name>pattern)'$text = 'Date: 2024-06-15' if ($text -match '(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})') { $matches['year'] $matches['month'] $matches['day'] }
$text = 'Name: John Doe' if ($text -match 'Name: (?<first>\w+) (?<last>\w+)') { "$($matches['first']) $($matches['last'])" }
$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.' }
(?<year>\d{4})?(?<name>pattern) labels the matched text as 'name'.(?<year>\d{4}) captures 4 digits and labels them 'year'.(?<name>pattern) for named captures.(?<day>\d{2}) uses (?<day>\d{2}), which is correct syntax for two digits named 'day'.$text = 'Date: 2023-07-15'
if ($text -match '(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})') {
"$($matches['year'])/$($matches['month'])/$($matches['day'])"
} else {
'No match'
}$text = 'User: JohnDoe'
if ($text -match '(?<user>\w+)') {
Write-Output $matches.user
}'Name: Jane Doe' using named captures in PowerShell. Which script correctly captures and prints them as "Doe, Jane"?$text = 'Name: Jane Doe'
if ($text -match 'Name: (?<first>\w+) (?<last>\w+)') {
"$($matches['last']), $($matches['first'])"
} does this correctly.$text = 'Name: Jane Doe'
if ($text -match 'Name: (?<first>\w+) (?<last>\w+)') {
"$($matches['last']), $($matches['first'])"
} [OK]Pass the test and this pattern moves unknown