I\'m not such a regex
expert and frankly I\'m trying to avoid it whenever I can.
I would like to create a new $String
where the number wit
If you want to avoid the regex:
$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
With regex:
$s = "\\Server\c$\share_1\share2_\Taget2[1] - 2014-07-29.log"
$s -replace "(?<=\[)(\d+)","bla"
Result:
\\Server\c$\share_1\share2_\Taget2[bla] - 2014-07-29.log
So you can do something like this:
$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
Result:
\\Server\c$\share_1\share2_\Taget2[2] - 2014-07-29.log
Another option is using the Replace() method of the Regex
class with a scriptblock (code taken from this answer by 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)
Existing files could be handled like this:
...
$re = [Regex]"\[(\d+)\]"
while (Test-Path -LiteralPath $filename) {
$filename = $re.Replace($filename, $callback)
}
Note that you must use Test-Path
with the parameter -LiteralPath
here, because your filename contains square brackets, which would otherwise be interpreted as wildcard characters.