PowerShell 技能连载 - 正则表达式实战
正则表达式基础
1 | # 邮箱验证模式 |
高级应用场景
批量重命名文件:
1
2Get-ChildItem *.log |
Rename-Item -NewName { $_.Name -replace '_\d{8}_','_$(Get-Date -f yyyyMMdd)_' }日志分析提取:
1
2
3
4
5
6
7Select-String -Path *.log -Pattern 'ERROR (\w+): (.+)' |
ForEach-Object {
[PSCustomObject]@{
Code = $_.Matches.Groups[1].Value
Message = $_.Matches.Groups[2].Value
}
}
最佳实践
使用命名捕获组增强可读性:
1
2
3
4$logEntry = '2024-04-22 14:35 [WARN] Disk space below 10%'
if ($logEntry -match '(?<Date>\d{4}-\d{2}-\d{2}).+\[(?<Level>\w+)\] (?<Message>.+)') {
$matches['Level']
}预编译常用模式提升性能:
1
2
3
4$ipPattern = [regex]::new('^\d{1,3}(\.\d{1,3}){3}$')
if ($ipPattern.IsMatch('192.168.1.1')) {
# IP地址验证逻辑
}多行模式处理复杂文本:
1
2$multiLineText = Get-Content -Raw data.txt
$matches = $multiLineText | Select-String -Pattern '(?s)<start>(.*?)<end>'
PowerShell 技能连载 - 正则表达式实战
http://blog.vichamp.com/2025/02/11/powershell-regex-application/