PowerShell Replace number in string

后端 未结 3 1272
日久生厌
日久生厌 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: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.

提交回复
热议问题