PowerShell: Regex Result ($Matches)

By Xah Lee. Date: .
$Matches
  • $Matches[0] → whole match string.
  • $Matches[1] → first captured string.
  • $Matches[2] → second captured string.
  • $Matches[name] → named captured string.

🛑 WARNING: they store only the first occurrence.

"2024-12-14" -match "(\d{4})-"
# True

Write-Output $matches[1]
# 2024

Write-Output $matches[0]
# 2024-
$x = '<a href="major_maps.html">big maps</a>'

# named capture
$x -match 'href="(?<hrefval>[^"]+)"'

Write-Host $matches["hrefval"]
# major_maps.html

PowerShell, string and regular expression