PowerShell判断字符串是否匹配正则

更新于 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]... 为分组内容
}

浙ICP备19039918号-1