问题描述
所以我现在所拥有的(下面)将搜索 XX-##-#
并将其强制为 XX-##-#0000
.
So what I have now will (below) will search for XX-##-#
and force it to XX-##-#0000
.
如何才能返回XX-##-0000#
?
有没有办法在末尾强制 5 位数字,填充前面的 0,以覆盖其他可能性(XX-##-##
, XX-##-###
, XX-##-####
)?相对于复制 4 次,每次稍微调整.
Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##
, XX-##-###
, XX-##-####
)? As opposed to copying this 4 times, slightly adjusting for each.
$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
运算符不支持将 表达式(脚本块)作为替换字符串,这里需要一个简洁的解决方案.
Unfortunately, PowerShell's -replace
operator doesn't support passing an expression (script block) as the replacement string, which a succinct solution would require here.
但是,您可以使用适当的[regex]
.NET 类型的 .Replace()
方法重载:
However, you can use 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
})
}
以上产生:
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
这篇关于Powershell 以字符串模式强制 5 位数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!