Bird
0
0

What will be the output of this PowerShell code?

medium📝 Command Output Q13 of 15
PowerShell - Regular Expressions
What will be the output of this PowerShell code?
$text = 'Date: 2023-07-15'
if ($text -match '(?\d{4})-(?\d{2})-(?\d{2})') {
  "$($matches['year'])/$($matches['month'])/$($matches['day'])"
} else {
  'No match'
}
A"2023/07/15"
B"Date: 2023-07-15"
C"No match"
D"2023-07-15"
Step-by-Step Solution
Solution:
  1. Step 1: Understand the regex and matching

    The regex captures year, month, and day as named groups from the string 'Date: 2023-07-15'.
  2. Step 2: Access named captures in $matches

    After matching, $matches['year'] = '2023', $matches['month'] = '07', $matches['day'] = '15'. The output formats them as "2023/07/15".
  3. Final Answer:

    "2023/07/15" -> Option A
  4. Quick Check:

    Named captures accessed = formatted date [OK]
Quick Trick: Use $matches['name'] to get named group values [OK]
Common Mistakes:
  • Expecting original string output
  • Using $matches.year instead of $matches['year']
  • Not matching regex correctly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes