scripts/RegexLab.ps1
13.4 KB| 1 | <# |
| 2 | RegexLab —— 正则表达式的匹配定位、替换预览与语法校验(PowerShell 7) |
| 3 | |
| 4 | 用法示例: |
| 5 | pwsh RegexLab.ps1 match -Pattern '\d+' -InputText 'abc123 def456' |
| 6 | pwsh RegexLab.ps1 match -Pattern '^(?<k>\w+)=(\d+)$' -Multiline -InputPath .\a.txt -Json |
| 7 | pwsh RegexLab.ps1 replace -Pattern '(\d{4})-(\d{2})-(\d{2})' -Replacement '$3/$2/$1' -InputText '2026-11-25' |
| 8 | pwsh RegexLab.ps1 split -Pattern '[,;]' -InputText 'a,b;c' |
| 9 | pwsh RegexLab.ps1 validate -Pattern '(?<name>x)+' |
| 10 | pwsh RegexLab.ps1 escape -InputText 'a.b*c' |
| 11 | |
| 12 | 退出码:0 成功(match 至少命中一条)/ 1 没有命中 / 2 正则语法错误 / 3 参数或输入错误 / 4 匹配超时 |
| 13 | #> |
| 14 | |
| 15 | param( |
| 16 | [Parameter(Mandatory = $true, Position = 0)] |
| 17 | [ValidateSet('match', 'replace', 'split', 'validate', 'escape')] |
| 18 | [string]$Action, |
| 19 | |
| 20 | [string]$Pattern, |
| 21 | [string]$InputText, |
| 22 | [string]$InputPath, |
| 23 | [string]$Replacement, |
| 24 | [int]$Count = 0, |
| 25 | [int]$Max = 50, |
| 26 | [switch]$CaseSensitive, |
| 27 | [switch]$Multiline, |
| 28 | [switch]$Singleline, |
| 29 | [switch]$IgnorePatternWhitespace, |
| 30 | [switch]$Json, |
| 31 | [string]$OutFile, |
| 32 | [switch]$InPlace, |
| 33 | [int]$TimeoutMs = 2000 |
| 34 | ) |
| 35 | |
| 36 | $ErrorActionPreference = 'Stop' |
| 37 | |
| 38 | function Fail { |
| 39 | param([string]$Message, [int]$Code) |
| 40 | [Console]::Error.WriteLine("错误: $Message") |
| 41 | exit $Code |
| 42 | } |
| 43 | |
| 44 | function Show-Value { |
| 45 | param([string]$Text) |
| 46 | if ($null -eq $Text) { return '' } |
| 47 | return $Text.Replace("`r", '\r').Replace("`n", '\n').Replace("`t", '\t') |
| 48 | } |
| 49 | |
| 50 | function Read-TextFile { |
| 51 | param([string]$Path) |
| 52 | $bytes = [IO.File]::ReadAllBytes($Path) |
| 53 | $hasBom = ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) |
| 54 | $offset = 0 |
| 55 | if ($hasBom) { $offset = 3 } |
| 56 | $text = [Text.Encoding]::UTF8.GetString($bytes, $offset, $bytes.Length - $offset) |
| 57 | return [pscustomobject]@{ Text = $text; Bom = $hasBom } |
| 58 | } |
| 59 | |
| 60 | function Write-TextFile { |
| 61 | param([string]$Path, [string]$Text, [bool]$Bom) |
| 62 | $enc = New-Object System.Text.UTF8Encoding($Bom) |
| 63 | [IO.File]::WriteAllText($Path, $Text, $enc) |
| 64 | } |
| 65 | |
| 66 | function Resolve-OutputPath { |
| 67 | param([string]$Path) |
| 68 | if ([IO.Path]::IsPathRooted($Path)) { return $Path } |
| 69 | return (Join-Path (Get-Location).ProviderPath $Path) |
| 70 | } |
| 71 | |
| 72 | function Get-Options { |
| 73 | param( |
| 74 | [bool]$CaseSensitive, |
| 75 | [bool]$Multiline, |
| 76 | [bool]$Singleline, |
| 77 | [bool]$IgnorePatternWhitespace |
| 78 | ) |
| 79 | $value = 0 |
| 80 | if (-not $CaseSensitive) { $value = $value -bor [int][System.Text.RegularExpressions.RegexOptions]::IgnoreCase } |
| 81 | if ($Multiline) { $value = $value -bor [int][System.Text.RegularExpressions.RegexOptions]::Multiline } |
| 82 | if ($Singleline) { $value = $value -bor [int][System.Text.RegularExpressions.RegexOptions]::Singleline } |
| 83 | if ($IgnorePatternWhitespace) { $value = $value -bor [int][System.Text.RegularExpressions.RegexOptions]::IgnorePatternWhitespace } |
| 84 | $list = @() |
| 85 | if (-not $CaseSensitive) { $list += 'ignorecase' } else { $list += 'case-sensitive' } |
| 86 | if ($Multiline) { $list += 'multiline' } |
| 87 | if ($Singleline) { $list += 'singleline' } |
| 88 | if ($IgnorePatternWhitespace) { $list += 'ignore-whitespace' } |
| 89 | return [pscustomobject]@{ |
| 90 | Value = [System.Text.RegularExpressions.RegexOptions]$value |
| 91 | Names = ($list -join ',') |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | function Compile-Regex { |
| 96 | param([string]$Pattern, [System.Text.RegularExpressions.RegexOptions]$Options, [int]$TimeoutMs) |
| 97 | try { |
| 98 | return [regex]::new($Pattern, $Options, [TimeSpan]::FromMilliseconds($TimeoutMs)) |
| 99 | } |
| 100 | catch { |
| 101 | $ex = $_.Exception |
| 102 | while ($null -ne $ex.InnerException) { $ex = $ex.InnerException } |
| 103 | $detail = $ex.Message |
| 104 | $isParseError = ($ex -is [System.Text.RegularExpressions.RegexParseException]) |
| 105 | if ($isParseError -and $ex.Offset -ge 0) { |
| 106 | $detail = "$detail(出错位置:模式串第 $([int]$ex.Offset + 1) 个字符起)" |
| 107 | } |
| 108 | [Console]::Error.WriteLine("正则语法错误: $detail") |
| 109 | exit 2 |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | function Get-GroupInfo { |
| 114 | param($Regex, $Match) |
| 115 | $names = $Regex.GetGroupNames() |
| 116 | $namedByNumber = @{} |
| 117 | foreach ($n in $names) { |
| 118 | if ($n -notmatch '^\d+$') { |
| 119 | $namedByNumber[[string]$Regex.GroupNumberFromName($n)] = $n |
| 120 | } |
| 121 | } |
| 122 | $parts = New-Object 'System.Collections.Generic.List[string]' |
| 123 | $map = [ordered]@{} |
| 124 | foreach ($n in $names) { |
| 125 | if ($n -eq '0') { continue } |
| 126 | if ($n -match '^\d+$' -and $namedByNumber.ContainsKey($n)) { continue } |
| 127 | $g = $Match.Groups[$n] |
| 128 | if ($null -eq $g -or -not $g.Success) { continue } |
| 129 | $key = $n |
| 130 | if ($n -match '^\d+$') { $key = '$' + $n } |
| 131 | $parts.Add("$key=" + (Show-Value $g.Value)) |
| 132 | $map[$key] = $g.Value |
| 133 | } |
| 134 | return [pscustomobject]@{ Display = ($parts -join ' '); Map = $map } |
| 135 | } |
| 136 | |
| 137 | if ($InPlace -and $OutFile) { Fail '-InPlace 与 -OutFile 不能同时使用,请二选一' 3 } |
| 138 | if ($InPlace -and [string]::IsNullOrEmpty($InputPath)) { Fail '-InPlace 需要配合 -InputPath 指定要原地修改的文件' 3 } |
| 139 | if ($Max -lt 1) { $Max = 50 } |
| 140 | if ($TimeoutMs -lt 1) { $TimeoutMs = 1 } |
| 141 | |
| 142 | $needsPattern = $true |
| 143 | if ($Action -eq 'escape') { $needsPattern = $false } |
| 144 | if ($needsPattern -and [string]::IsNullOrEmpty($Pattern)) { Fail "-Action $Action 需要 -Pattern 指定正则表达式" 3 } |
| 145 | |
| 146 | # ---- 收集输入文本 ---- |
| 147 | $text = $null |
| 148 | $sourceBom = $false |
| 149 | $sourcePath = '' |
| 150 | |
| 151 | if ($Action -in @('match', 'replace', 'split')) { |
| 152 | if ($PSBoundParameters.ContainsKey('InputText')) { |
| 153 | $text = $InputText |
| 154 | } |
| 155 | elseif (-not [string]::IsNullOrEmpty($InputPath)) { |
| 156 | $full = Resolve-OutputPath $InputPath |
| 157 | if (-not (Test-Path -LiteralPath $full)) { Fail "找不到输入文件: $InputPath" 3 } |
| 158 | $r = Read-TextFile $full |
| 159 | $text = $r.Text |
| 160 | $sourceBom = $r.Bom |
| 161 | $sourcePath = $full |
| 162 | } |
| 163 | if ($null -eq $text) { Fail '缺少输入内容:请用 -InputText 或 -InputPath 提供文本' 3 } |
| 164 | |
| 165 | # 行首偏移,用于把字符下标换算成行列 |
| 166 | $starts = New-Object 'System.Collections.Generic.List[int]' |
| 167 | $starts.Add(0) |
| 168 | foreach ($nl in [regex]::Matches($text, "`n")) { $starts.Add($nl.Index + 1) } |
| 169 | |
| 170 | function Get-Position { |
| 171 | param([int]$Index) |
| 172 | $lo = 0 |
| 173 | $hi = $starts.Count - 1 |
| 174 | while ($lo -lt $hi) { |
| 175 | $mid = [int][Math]::Floor(($lo + $hi + 1) / 2) |
| 176 | if ($starts[$mid] -le $Index) { $lo = $mid } else { $hi = $mid - 1 } |
| 177 | } |
| 178 | return @(($lo + 1), ($Index - $starts[$lo] + 1)) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | # ---- escape 动作 ---- |
| 183 | if ($Action -eq 'escape') { |
| 184 | $literal = $InputText |
| 185 | if (-not $PSBoundParameters.ContainsKey('InputText')) { |
| 186 | if (-not [string]::IsNullOrEmpty($Pattern)) { $literal = $Pattern } |
| 187 | elseif ($input) { $literal = ((@($input) | ForEach-Object { [string]$_ }) -join "`n") } |
| 188 | } |
| 189 | if ([string]::IsNullOrEmpty($literal)) { Fail 'escape 需要 -InputText 提供要转义的普通文本' 3 } |
| 190 | $escaped = [regex]::Escape($literal) |
| 191 | if ($Json) { |
| 192 | [pscustomobject]@{ action = 'escape'; literal = $literal; escaped = $escaped } | ConvertTo-Json -Depth 4 |
| 193 | } |
| 194 | else { |
| 195 | Write-Output $escaped |
| 196 | } |
| 197 | exit 0 |
| 198 | } |
| 199 | |
| 200 | $optInfo = Get-Options -CaseSensitive:$CaseSensitive.IsPresent -Multiline:$Multiline.IsPresent -Singleline:$Singleline.IsPresent -IgnorePatternWhitespace:$IgnorePatternWhitespace.IsPresent |
| 201 | $rx = Compile-Regex -Pattern $Pattern -Options $optInfo.Value -TimeoutMs $TimeoutMs |
| 202 | |
| 203 | # ---- validate 动作 ---- |
| 204 | if ($Action -eq 'validate') { |
| 205 | if ($Json) { |
| 206 | [pscustomobject]@{ |
| 207 | action = 'validate' |
| 208 | valid = $true |
| 209 | pattern = $Pattern |
| 210 | options = $optInfo.Names |
| 211 | groups = @($rx.GetGroupNames() | Where-Object { $_ -ne '0' }) |
| 212 | } | ConvertTo-Json -Depth 5 |
| 213 | } |
| 214 | else { |
| 215 | Write-Output '正则语法正常' |
| 216 | Write-Output "pattern: $Pattern" |
| 217 | Write-Output "options: $($optInfo.Names)" |
| 218 | $names = @($rx.GetGroupNames() | Where-Object { $_ -ne '0' }) |
| 219 | Write-Output "groups: $(($names -join ', '))" |
| 220 | } |
| 221 | exit 0 |
| 222 | } |
| 223 | |
| 224 | # ---- match 动作 ---- |
| 225 | if ($Action -eq 'match') { |
| 226 | $total = 0 |
| 227 | $rows = New-Object 'System.Collections.Generic.List[string]' |
| 228 | $items = New-Object 'System.Collections.Generic.List[object]' |
| 229 | |
| 230 | try { |
| 231 | foreach ($m in $rx.Matches($text)) { |
| 232 | $total++ |
| 233 | $pos = Get-Position $m.Index |
| 234 | $info = Get-GroupInfo -Regex $rx -Match $m |
| 235 | if ($Json) { |
| 236 | $items.Add([ordered]@{ |
| 237 | index = $m.Index |
| 238 | length = $m.Length |
| 239 | line = $pos[0] |
| 240 | column = $pos[1] |
| 241 | value = $m.Value |
| 242 | groups = $info.Map |
| 243 | }) |
| 244 | } |
| 245 | if ($rows.Count -lt $Max) { |
| 246 | $val = Show-Value $m.Value |
| 247 | if ($val.Length -gt 40) { $val = $val.Substring(0, 40) + '…' } |
| 248 | $rows.Add(('{0,-4} {1,-12} {2,-5} {3,-42} {4}' -f $total, "$($pos[0]):$($pos[1])", $m.Length, $val, $info.Display)) |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | catch [System.Text.RegularExpressions.RegexMatchTimeoutException] { |
| 253 | [Console]::Error.WriteLine("匹配超时:${TimeoutMs}ms 内未完成。这通常意味着正则会回溯爆炸,请换用更精确的写法或适当提高 -TimeoutMs") |
| 254 | exit 4 |
| 255 | } |
| 256 | |
| 257 | if ($Json) { |
| 258 | [pscustomobject]@{ |
| 259 | action = 'match' |
| 260 | pattern = $Pattern |
| 261 | options = $optInfo.Names |
| 262 | timeoutMs = $TimeoutMs |
| 263 | matchCount = $total |
| 264 | truncated = ($total -gt $Max) |
| 265 | matches = @($items.ToArray()) |
| 266 | } | ConvertTo-Json -Depth 8 |
| 267 | } |
| 268 | else { |
| 269 | Write-Output "pattern: $Pattern" |
| 270 | Write-Output "options: $($optInfo.Names) timeout: ${TimeoutMs}ms" |
| 271 | if ($total -gt $Max) { |
| 272 | Write-Output "matches: $total(仅显示前 $Max 条)" |
| 273 | } |
| 274 | else { |
| 275 | Write-Output "matches: $total" |
| 276 | } |
| 277 | if ($total -gt 0) { |
| 278 | Write-Output ('{0,-4} {1,-12} {2,-5} {3,-42} {4}' -f '#', 'LINE:COL', 'LEN', 'MATCH', 'GROUPS') |
| 279 | foreach ($row in $rows) { Write-Output $row } |
| 280 | } |
| 281 | } |
| 282 | if ($total -gt 0) { exit 0 } |
| 283 | exit 1 |
| 284 | } |
| 285 | |
| 286 | # ---- replace 动作 ---- |
| 287 | if ($Action -eq 'replace') { |
| 288 | $rep = '' |
| 289 | if ($PSBoundParameters.ContainsKey('Replacement')) { $rep = $Replacement } |
| 290 | |
| 291 | $sb = New-Object System.Text.StringBuilder |
| 292 | $last = 0 |
| 293 | $hits = 0 |
| 294 | try { |
| 295 | foreach ($m in $rx.Matches($text)) { |
| 296 | if ($Count -gt 0 -and $hits -ge $Count) { break } |
| 297 | [void]$sb.Append($text.Substring($last, $m.Index - $last)) |
| 298 | [void]$sb.Append($m.Result($rep)) |
| 299 | $last = $m.Index + $m.Length |
| 300 | $hits++ |
| 301 | } |
| 302 | } |
| 303 | catch [System.Text.RegularExpressions.RegexMatchTimeoutException] { |
| 304 | [Console]::Error.WriteLine("匹配超时:${TimeoutMs}ms 内未完成,替换未执行。请简化正则或提高 -TimeoutMs") |
| 305 | exit 4 |
| 306 | } |
| 307 | [void]$sb.Append($text.Substring($last)) |
| 308 | $result = $sb.ToString() |
| 309 | |
| 310 | $written = '' |
| 311 | $outPath = '' |
| 312 | if ($InPlace -or -not [string]::IsNullOrEmpty($OutFile)) { |
| 313 | if ($InPlace) { $outPath = $sourcePath } |
| 314 | else { $outPath = Resolve-OutputPath $OutFile } |
| 315 | $bom = $sourceBom |
| 316 | Write-TextFile -Path $outPath -Text $result -Bom $bom |
| 317 | $written = $outPath |
| 318 | } |
| 319 | |
| 320 | if ($Json) { |
| 321 | $obj = [ordered]@{ |
| 322 | action = 'replace' |
| 323 | pattern = $Pattern |
| 324 | replacement = $rep |
| 325 | replacements = $hits |
| 326 | written = $written |
| 327 | } |
| 328 | if ([string]::IsNullOrEmpty($written)) { $obj['text'] = $result } |
| 329 | [pscustomobject]$obj | ConvertTo-Json -Depth 5 |
| 330 | } |
| 331 | else { |
| 332 | Write-Output "replacements: $hits" |
| 333 | if ([string]::IsNullOrEmpty($written)) { |
| 334 | Write-Output '---- 替换后文本 ----' |
| 335 | Write-Output $result |
| 336 | } |
| 337 | else { |
| 338 | $size = (Get-Item -LiteralPath $written).Length |
| 339 | $bomText = '无 BOM' |
| 340 | if ($sourceBom) { $bomText = '有 BOM' } |
| 341 | Write-Output "已写入: $outPath ($size 字节,$bomText)" |
| 342 | } |
| 343 | } |
| 344 | exit 0 |
| 345 | } |
| 346 | |
| 347 | # ---- split 动作 ---- |
| 348 | if ($Action -eq 'split') { |
| 349 | try { |
| 350 | $pieces = $rx.Split($text) |
| 351 | } |
| 352 | catch [System.Text.RegularExpressions.RegexMatchTimeoutException] { |
| 353 | [Console]::Error.WriteLine("匹配超时:${TimeoutMs}ms 内未完成,切分未执行") |
| 354 | exit 4 |
| 355 | } |
| 356 | |
| 357 | $offset = 0 |
| 358 | $items = New-Object 'System.Collections.Generic.List[object]' |
| 359 | $i = 0 |
| 360 | foreach ($piece in $pieces) { |
| 361 | $pos = Get-Position $offset |
| 362 | $items.Add([ordered]@{ |
| 363 | index = $i |
| 364 | line = $pos[0] |
| 365 | column = $pos[1] |
| 366 | value = $piece |
| 367 | length = $piece.Length |
| 368 | }) |
| 369 | $offset += $piece.Length |
| 370 | $i++ |
| 371 | } |
| 372 | |
| 373 | if ($Json) { |
| 374 | [pscustomobject]@{ |
| 375 | action = 'split' |
| 376 | pattern = $Pattern |
| 377 | options = $optInfo.Names |
| 378 | pieceCount = $pieces.Count |
| 379 | pieces = @($items.ToArray()) |
| 380 | } | ConvertTo-Json -Depth 8 |
| 381 | } |
| 382 | else { |
| 383 | Write-Output "pattern: $Pattern options: $($optInfo.Names)" |
| 384 | Write-Output "pieces: $($pieces.Count)" |
| 385 | foreach ($it in $items) { |
| 386 | $val = Show-Value $it.value |
| 387 | if ($val.Length -gt 60) { $val = $val.Substring(0, 60) + '…' } |
| 388 | Write-Output ('{0,-4} {1,-12} {2,-5} {3}' -f $it.index, "$($it.line):$($it.column)", $it.length, $val) |
| 389 | } |
| 390 | } |
| 391 | exit 0 |
| 392 | } |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

