Bird
0
0

Why does this code fail?

medium📝 Debug Q7 of 15
PowerShell - String Operations
Why does this code fail?
$text = 'abc'
if ($text -match '\d+') { $Matches[0] }
AMissing quotes around $Matches
BNo match found, so $Matches is empty and accessing [0] causes error
CNo error; code runs fine
DPowerShell does not support -match with digits
Step-by-Step Solution
Solution:
  1. Step 1: Check if regex matches string

    The string 'abc' has no digits, so -match '\d+' returns false.
  2. Step 2: Evaluate the if statement

    Since the condition is false, the block with $Matches[0] is not executed, so no error occurs. The code runs fine.
  3. Final Answer:

    No error; code runs fine -> Option C
  4. Quick Check:

    if condition prevents access to $Matches [OK]
Quick Trick: if (-match) protects $Matches access [OK]
Common Mistakes:
  • Assuming $Matches always has data
  • Ignoring match result before accessing $Matches
  • Thinking regex is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes