regex - Powershell以字符串模式显示的5位数字格式

标签 regex powershell text return-value

因此,我现在(下面)将搜索XX-##-#并将其强制为XX-##-#0000

我该怎么做才能返回XX-##-0000#

有没有办法在结尾处强制5位数字(填充前面的0)来覆盖其他可能性(XX-##-##XX-##-###XX-##-####)?与将其复制4次相比,每次略有调整。

$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ | 
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) | 
     Set-Content $_
}

谢谢。

编辑:我想执行以下操作
Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####

最佳答案

不幸的是,PowerShell的-replace运算符不支持将表达式(脚本块)作为替换字符串传递,这在此处是简洁的解决方案。

但是,您可以使用the appropriate [regex] .NET type's .Replace() method overload:

注意:此解决方案仅针对基于正则表达式的替换部分,但是很容易将其嵌入到问题的较大管道中。

# Define sample array.
$lines = @'
Line 1 AB-00-0 and also AB-01-1
Line 2 CD-02-22 after
Line 3 EF-03-333 it
Line 4 GH-04-4444 goes 
Line 5 IJ-05-55555 on
'@ -split "`n"

# Loop over lines...
$lines | ForEach-Object {
  # ... and use a regex with 2 capture groups to capture the substrings of interest
  #     and use a script block to piece them together with number padding
  #     applied to the 2nd group
  ([regex] '\b([a-zA-Z]{2}-[0-9]{2}-)([0-9]+)').Replace($_, { 
    param($match)
    $match.Groups[1].Value + '{0:D5}' -f [int] $match.Groups[2].Value
  })
}

以上 yield :
Line 1 AB-00-00000 and also AB-01-00001
Line 2 CD-02-00022 after
Line 3 EF-03-00333 it
Line 4 GH-04-04444 goes 
Line 5 IJ-05-55555 on

关于regex - Powershell以字符串模式显示的5位数字格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44416861/

相关文章:

正则表达式:删除包含 "help"等的行

mysql - 在 mysql 5.0 中将文件与 REGEXP 进行比较

PHP正则表达式的单词短语语法?

运行脚本时的安全警告 - Unblock-File not unblocking file

c++ - QTextStream 按点对齐(小数分隔符)

c# - Regex.Match 简单数组

windows - Powershell Open可执行文件,带有Program Files\WindowsApps内部的“开始”进程-拒绝访问

Powershell 以具有提升权限的另一个用户身份运行

c# - 计算文本文件中特定单词的频率

c# - 使用条形码字体打印