约 2100 字

约 11 分钟

#正则表达式

PowerShell 的字符串运算符和 [regex] 类都基于 .NET 正则表达式。常用运算符有 -match、-notmatch、-replace 和 -split,它们默认不区分大小写,对应的 -cmatch、-creplace、-csplit 则区分大小写。

#匹配测试

-match 判断左侧字符串是否匹配右侧模式,返回布尔值:

> 'server-01' -match '^server-\d+$'
> 'server-01' -notmatch '^db-'

#$matches

-match 匹配成功后,自动变量 $matches 保存匹配结果。键 0 表示整个匹配,1、2 等表示捕获组:

> 'server-01' -match '^([a-z]+)-(\d+)$'
> $matches[0]
> $matches[1]

注意匹配失败时 $matches 可能保留上一次的结果,使用前应先检查 -match 的返回值。

#替换

-replace 用正则表达式查找并替换:

> 'a1b2c3' -replace '\d', '#'

替换字符串中可以使用 $1、$2 引用捕获组:

> 'Tom,88' -replace '(\w+),(\d+)', '$1: $2'

需要区分大小写时使用 -creplace。

#拆分

-split 按正则表达式拆分字符串:

> 'a,b;c' -split '[,;]'
> 'a1b2c3' -split '\d'
  • 连续分隔符会产生空字符串,需要时可用 Where-Object 过滤。
  • 区分大小写时使用 -csplit。

#命名分组

使用 (?<名称>模式) 定义命名分组,比数字编号更易读:

> 'server-01' -match '^(?<role>[a-z]+)-(?<id>\d+)$'
> $matches['role']

在替换字符串中通过 ${名称} 引用:

> 'Tom,88' -replace '(?<name>\w+),(?<score>\d+)', '${name}: ${score}'

#[regex] 类

静态方法适合需要更多控制的场景:

> [regex]::IsMatch('abc123', '\d+')
> [regex]::Match('abc123', '\d+').Value
> [regex]::Replace('a1b2', '\d', '#')
> [regex]::Escape('a.b')

#Select-String

Select-String 在文件中按正则表达式查找,并返回匹配对象:

> Select-String -Path ./app.log -Pattern 'ERROR'
> Select-String -Path ./app.log -Pattern 'ERROR' -Context 1, 2
> Select-String -Path ./app.log -Pattern '(\w+)=(\d+)' -AllMatches
  • -Context 显示匹配行前后的上下文。
  • -AllMatches 返回一行中的所有匹配,而不是只返回第一个。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2