Bird
0
0

How can you use regex in PowerShell to replace all sequences of whitespace with a single space in a string?

hard📝 Application Q9 of 15
PowerShell - Regular Expressions
How can you use regex in PowerShell to replace all sequences of whitespace with a single space in a string?
A$text -match '\s+', ' '
B$text -replace '\s+', ' '
C$text -like '\s+', ' '
D$text -contains '\s+', ' '
Step-by-Step Solution
Solution:
  1. Step 1: Identify the correct operator for replacement

    PowerShell uses '-replace' to substitute regex matches with new text.
  2. Step 2: Confirm regex pattern and replacement

    '\s+' matches one or more whitespace; replacing with single space achieves the goal.
  3. Final Answer:

    $text -replace '\s+', ' ' -> Option B
  4. Quick Check:

    Use -replace for regex substitutions [OK]
Quick Trick: Use -replace with '\s+' to normalize whitespace [OK]
Common Mistakes:
  • Using -match or -like for replacements
  • Confusing -contains with regex operators
  • Not using quantifier '+' for multiple spaces

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes