[英]PowerShell Replace number in string
我不是这样的regex
专家,坦率地说,我会尽量避免使用它。
我想创建一个新的$String
,其中$String
中的数字用+1
更新。 该数字可以是一位数或两位数,并且始终在两个括号之间。
从:
$String = "\\Server\c$\share_1\share2_\Taget2[1] - 2014-07-29.log"
至:
$String = "\\Server\c$\share_1\share2_\Taget2[2] - 2014-07-29.log"
谢谢您的帮助。
如果要避免使用正则表达式:
$String = "\\Server\c$\share_1\share2_\Taget2[1] - 2014-07-29.log"
$parts = $string.Split('[]')
$Newstring = '{0}[{1}]{2}' -f $parts[0],(1 + $parts[1]),$parts[2]
$Newstring
\\Server\c$\share_1\share2_\Taget2[2] - 2014-07-29.log
另一个选择是将Regex
类的Replace()
方法与脚本块一起使用(Roman Kuzmin从此答案中获取的代码):
$callback = {
$v = [int]$args[0].Groups[1].Value
$args[0] -replace $v,++$v
}
$filename = "\\Server\c$\share_1\share2_\Taget2[1] - 2014-07-29.log"
$re = [Regex]"\[(\d+)\]"
$re.Replace($filename, $callback)
现有文件可以这样处理:
...
$re = [Regex]"\[(\d+)\]"
while (Test-Path -LiteralPath $filename) {
$filename = $re.Replace($filename, $callback)
}
请注意,此处必须将Test-Path
与-LiteralPath
参数-LiteralPath
,因为文件名包含方括号,否则将被解释为通配符 。
使用正则表达式:
$s = "\\Server\c$\share_1\share2_\Taget2[1] - 2014-07-29.log"
$s -replace "(?<=\[)(\d+)","bla"
结果:
\\Server\c$\share_1\share2_\Taget2[bla] - 2014-07-29.log
因此,您可以执行以下操作:
$s = "\\Server\c$\share_1\share2_\Taget2[1] - 2014-07-29.log"
$s -match "(?<=\[)(\d+)" | Out-Null ## find regex matches
$newNumber = [int]$matches[0] + 1
$s -replace "(?<=\[)(\d+)",$newNumber
结果:
\\Server\c$\share_1\share2_\Taget2[2] - 2014-07-29.log
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.