DarkLite1
DarkLite1

Reputation: 14705

PowerShell Replace number in string

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 within the string is updated with +1. This number can be one or two digits and will always be between 2 brackets.

From:

$String = "\\Server\c$\share_1\share2_\Taget2[1] - 2014-07-29.log"

To:

$String = "\\Server\c$\share_1\share2_\Taget2[2] - 2014-07-29.log"

Thank you for your help.

Upvotes: 0

Views: 2812

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

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.

Upvotes: 1

Raf
Raf

Reputation: 10107

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

Upvotes: 0

mjolinor
mjolinor

Reputation: 68263

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

Upvotes: 4

Related Questions