Bird
0
0

You want to extract all email addresses from a list of strings stored in $lines. Which PowerShell snippet correctly uses -match and $matches to collect emails into $emails?

hard📝 Application Q15 of 15
PowerShell - String Operations
You want to extract all email addresses from a list of strings stored in $lines. Which PowerShell snippet correctly uses -match and $matches to collect emails into $emails?
A$emails = foreach ($line in $lines) { if ($line -match '[\w.-]+@[\w.-]+\.\w+') { $matches[0] } }
B$emails = $lines -match '[\w.-]+@[\w.-]+\.\w+'
C$emails = $lines | Where-Object { $_ -contains '[\w.-]+@[\w.-]+\.\w+' }
D$emails = foreach ($line in $lines) { $line -match '[\w.-]+@[\w.-]+\.\w+' }
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to loop and match each line

    We must check each line with -match and if it matches, collect the matched email from $matches[0].
  2. Step 2: Evaluate each option

    $emails = foreach ($line in $lines) { if ($line -match '[\w.-]+@[\w.-]+\.\w+') { $matches[0] } } loops through lines, tests with -match, and collects matched emails correctly. $emails = $lines -match '[\w.-]+@[\w.-]+\.\w+' tries to match the whole array at once, which doesn't work. $emails = $lines | Where-Object { $_ -contains '[\w.-]+@[\w.-]+\.\w+' } uses -contains which does not support regex. $emails = foreach ($line in $lines) { $line -match '[\w.-]+@[\w.-]+\.\w+' } runs -match but does not collect matched emails.
  3. Final Answer:

    $emails = foreach ($line in $lines) { if ($line -match '[\w.-]+@[\w.-]+\.\w+') { $matches[0] } } -> Option A
  4. Quick Check:

    Loop + -match + $matches[0] collects matches [OK]
Quick Trick: Use foreach + if (-match) + $matches[0] to collect matches [OK]
Common Mistakes:
  • Trying to match the whole array at once
  • Using -contains instead of -match for regex
  • Not collecting $matches[0] inside the loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes