POWERSHELL / CHAPTER 05

Regex captures with explicit success checks

Intermediate

Keep match state tied to the input that produced it.

By the end of this chapter

  • Read named captures after a successful scalar match
  • Avoid stale Matches values
  • Distinguish collection filtering from scalar matching

The idea

For a scalar string, -match returns a Boolean and a successful match populates the automatic Matches hashtable. Named groups make the meaning of captured text clear. Read captures inside the successful branch and validate conversion to the intended type. A regex describes an input shape; it does not automatically establish every business rule, numeric range, or encoding assumption your program needs.

Matches is stateful. A later failed match does not clear an earlier successful capture, so reading it unconditionally can accidentally reuse old data. With a collection on the left, -match filters matching elements and does not populate Matches in the same way as a scalar match. Keep each parsing operation narrow, give errors a deliberate path, and choose case-sensitive variants when the input contract requires them.

PowerShell example
if ('id:12' -match '^id:(?<Number>[0-9]+)$') {
    [int]$Matches.Number + 1
} else {
    'Invalid identifier'
}
Result
13

A successful anchored match captures 12. The branch converts that captured text before adding one.

Try it yourself

Parse a sequence of labeled counts, producing either a typed record or a clear validation result for each input.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Why should code read $Matches.Number inside the successful if branch?