更新于 2025-10-03
在 PowerShell 中判断一个字符串是否匹配正则,可以使用 -match
操作符,示例如下:
# 示例字符串
$str = "abc123"
# 示例正则表达式
$regex = "^[a-z]+\d+$"
# 判断是否匹配
if ($str -match $regex) {
Write-Output "匹配"
} else {
Write-Output "不匹配"
}
说明:
$str -match $regex
会返回 $true
或 $false
。$matches
自动保存匹配内容。$str -match $regex # 匹配返回 True,不匹配返回 False
if ($str -match $regex) {
$matches[0] # 整体匹配结果
# $matches[1], $matches[2]... 为分组内容
}