代码之家  ›  专栏  ›  技术社区  ›  Soleil

如何在powershell中[int]添加[string]regex替换?

  •  1
  • Soleil  · 技术社区  · 7 年前

    我正在用regex替换重命名文件:

    ls *dat | rename-item -newname {$_.name -replace '(.*)_([0-9]+)(.dat)','$1($2)$3'}
    

    但我也要加上 constant int [string]$2 ;类似于:

    '$1(@{int.parse($2)+3})($3)'
    

    我该怎么做?

    1 回复  |  直到 7 年前
        1
  •  1
  •   mklement0    7 年前

    PowerShell 核心 6.1.0版+ 支架 通过 脚本块 作为
    -replace 操作人员
    ;为找到的每个匹配调用脚本块,其输出形成替换字符串,因此 有可能 算法 替代品 (而不仅仅是 文本的 一个):

    'foo_10.dat' -replace '(.*)_([0-9]+)(\.dat)', { 
      '{0}{1}{2}' -f $_.Groups[1].Value, 
                     ([int] $_.Groups[2].Value + 3), 
                     $_.Groups[3].Value
    }
    

    上述结果:

    foo13.dat
    

    注意如何 3 已添加到 10 (删除下划线):

    $_ 在脚本块中是 [System.Text.RegularExpressions.Match] 表示匹配结果的实例;例如。, $_.Value 表示完全匹配,而 $_.Groups[1].Value 表示第一个捕获组匹配的内容。

    该功能建立在 [regex] .NET type's .Replace() method ,也可以直接(但不太容易)在早期的PowerShell版本中使用-请参见下文。


    Windows PowerShell 你有两个 选项 :

    • 使用 -match 运算符,然后根据automatic中反映的匹配信息在单独的语句中执行转换 $Matches 变量,由建议 kuujinbo :

      $null = 'foo_10.dat' -match '(.*)_([0-9]+)(\.dat)' # match first
      '{0}{1}{2}' -f $Matches.1, ([int] $Matches.2 + 3), $Matches.3 # build via $Matches
      
    • 直接使用.NET框架,脚本块作为 代表 (回调函数)到上述 [regex]::Replace() 方法,如 Ansgar Wiechers :

      ([regex] '(.*)_([0-9]+)(\.dat)').Replace('foo_10.dat', {
        param($match)
        '{0}{1}{2}' -f $match.Groups[1].Value, ([int] $match.Groups[2].Value + 3), $match.Groups[3].Value
      })
      
      • 注意形式参数- param($match) -必须在此处声明才能访问匹配结果,而顶部的纯PowerShell解决方案能够使用 美元 ,一如往常。