0
0
PowerShellscripting~10 mins

Named captures in PowerShell - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to capture the year from the date string using named captures.

PowerShell
$date = '2024-06-15'
if ($date -match '(?<year>\d{4})-\d{2}-\d{2}') {
    Write-Output $matches.[1]
}
Drag options to blanks, or click blank then click option'
Ayear
Bmonth
Cday
Ddate
Attempts:
3 left
💡 Hint
Common Mistakes
Using $matches.month or $matches.day which are not defined in the regex.
Trying to access $matches['year'] instead of $matches.year.
2fill in blank
medium

Complete the code to extract the 'name' from the string using named captures.

PowerShell
$text = 'Name: John Doe'
if ($text -match 'Name: (?<[1]>\w+ \w+)') {
    Write-Output $matches.name
}
Drag options to blanks, or click blank then click option'
Ausername
Bfullname
Cname
Dperson
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different group name than 'name' causing $matches.name to be empty.
Forgetting to name the capture group.
3fill in blank
hard

Fix the error in the regex to correctly capture 'hour' as a named group.

PowerShell
$time = '13:45'
if ($time -match '(?<[1]>\d{2}):\d{2}') {
    Write-Output $matches.hour
}
Drag options to blanks, or click blank then click option'
Ahr
Bhour
Chours
Dh
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different group name like 'hours' or 'hr' causing $matches.hour to be null.
Missing the named capture syntax.
4fill in blank
hard

Fill both blanks to capture 'day' and 'month' from the date string.

PowerShell
$date = '15/06/2024'
if ($date -match '(?<[1]>\d{2})/(?<[2]>\d{2})/\d{4}') {
    Write-Output "Day: $($matches.day), Month: $($matches.month)"
}
Drag options to blanks, or click blank then click option'
Aday
Byear
Cmonth
Ddate
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping day and month group names.
Using incorrect group names that don't match $matches properties.
5fill in blank
hard

Fill all three blanks to capture 'first', 'middle', and 'last' names from the string.

PowerShell
$fullName = 'John Michael Doe'
if ($fullName -match '(?<[1]>\w+) (?<[2]>\w+) (?<[3]>\w+)') {
    Write-Output "First: $($matches.first), Middle: $($matches.middle), Last: $($matches.last)"
}
Drag options to blanks, or click blank then click option'
Afirst
Bmiddle
Clast
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using generic group names like 'name' instead of specific ones.
Not matching group names to the variables used in Write-Output.