如何在Powershell中的文本字符串中的其他字符之前和之后添加字符

如何在Powershell中的文本字符串中的其他字符之前和之后添加字符,powershell,Powershell,我的代码使用regex(.*)从另一个文件捕获一个数字字符串。至少应该有四个数字 输出可能是 1456或234567 但我们可以说是 3667876 我想在最后三位数前加上“km”,在最后三位数后加上“m”。所以导致 3667公里876米 Powershell脚本中的代码行是 Get-Content -Tail 0 -Wait -Encoding "UTF8" $log | Select-String "Run Distance: (.*)" | % {"Total Distance

我的代码使用regex(.*)从另一个文件捕获一个数字字符串。至少应该有四个数字

输出可能是

1456或234567

但我们可以说是

3667876

我想在最后三位数前加上“km”,在最后三位数后加上“m”。所以导致

3667公里876米

Powershell脚本中的代码行是

Get-Content -Tail 0 -Wait -Encoding "UTF8" $log | 
  Select-String "Run Distance: (.*)" |
   % {"Total Distance `- " + $_.matches.groups[1].value} |
    Write-SlowOutput -outputFile $output -waitFor $delay
因此,在这种情况下,输出将读取

总距离-3667公里876米

任何人都可以帮助使用正则表达式来代替此Powershell脚本中的(.*)


谢谢

我没有
Write-SlowOutput
cmdlet,但是
ForEach-Object
cmdlet的输出看起来很好:

Get-Content -Tail 0 -Wait -Encoding "UTF8" $log | 
    Select-String "Run Distance: (\d+)(\d{3})$" |
    % {"Total Distance `- $($_.matches.groups[1].value)km $($_.matches.groups[2].value)m"} |
    Write-SlowOutput -outputFile $output -waitFor $delay

我在正则表达式中实现了两个匹配组,以便能够单独处理它们。

如果您喜欢更可读的代码,也可以通过使用
ToString()
将整数转换为字符串,然后使用
Substring()
将其切分,从而轻松实现这一点。结果很容易阅读

ForEach($n in $nums){
    $splitIndex = $n.ToString().Length - 3    
    $KMs =  $n.ToString().Substring(0,$splitIndex)
    $Meters = $n.ToString().SubString($splitIndex, 3)
    "Total distance $KMs Kilos - $Meters meters"
}
导致

Total distance 3667 Kilos - 876 meters
Total distance 33667 Kilos - 876 meters
Total distance 45454 Kilos - 131 meters

这里还有另一种方法来完成这项工作。[grin]您可以使用带有
-replace
运算符的正则表达式模式替换字符串中的数字,并使用匹配组构建新字符串。像这样

'1234' -replace '(.+)(.{3})$', '$1km $2m'
输出=
1km 234m

这方面的问题是,数字必须至少有4位才能正常工作。如果要使用的数字较少,则需要类似于
Thomas
FoxDeploy
的解决方案