【问题标题】:How to replace a string between two other strings如何在其他两个字符串之间替换一个字符串
【发布时间】:2015-09-27 15:16:38
【问题描述】:

我正在尝试在几个文件中替换以下类型的字符串:

StringResourceHelper.[STRING_OF_INTEREST]ResourceString()字符串。[STRING_OF_INTEREST]

例如我想替换:

StringResourceHelper.HelpResourceString()Strings.Help

到目前为止,如果第二个字符串不重要,我得到了一个简单的替换:

    Get-ChildItem . *.cs -Recurse |
      Foreach-Object {
       $c = ($_ | Get-Content) 
       $c = $c -replace 'StringResourceHelper.','Strings.'
       $c | Set-Content $_.FullName -Encoding UTF8
    }

但这对我没有帮助,因为我也有像 StringResourceHelper.Culture 这样的字符串,不应该被触及。

感谢任何帮助。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您需要在正则表达式中转义文字点,否则. 将匹配除换行符以外的任何字符。像这样的东西应该可以工作:

    $c = $c -replace 'StringResourceHelper\.(\w*?)ResourceString\(\)', 'Strings.$1'
    

    另外,您的代码可以稍微简化一下,如下所示:

    $srch = 'StringResourceHelper\.(\w*?)ResourceString\(\)'
    $repl = 'Strings.$1'
    
    Get-ChildItem . *.cs -Recurse | % {
       $filename = $_.FullName
       (Get-Content $filename) -replace $srch, $repl |
           Set-Content $filename -Encoding UTF8
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多