PowerShell Replace number in string

后端 未结 3 1248
日久生厌
日久生厌 2020-12-22 06:09

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

相关标签:
3条回答
  • 2020-12-22 06:23

    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
    
    0 讨论(0)
  • 2020-12-22 06:29

    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
    
    0 讨论(0)
  • 2020-12-22 06:31

    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.

    0 讨论(0)
提交回复
热议问题