【问题标题】:Replacing last occurrence of substring in string替换字符串中最后出现的子字符串
【发布时间】:2021-06-07 21:21:24
【问题描述】:

如何替换字符串中最后次出现的子字符串?

【问题讨论】:

    标签: powershell replace


    【解决方案1】:

    正则表达式也可以执行此任务。这是一个可行的示例。它将用“Bumblebee Joe”替换最后出现的“Aquarius”

    $text = "This is the dawning of the age of Aquarius. The age of Aquarius, Aquarius, Aquarius, Aquarius, Aquarius"
    $text -replace "(.*)Aquarius(.*)", '$1Bumblebee Joe$2'
    This is the dawning of the age of Aquarius. The age of Aquarius, Aquarius, Aquarius, Aquarius, Bumblebee Joe
    

    贪婪的量词确保它可以尽其所能直到Aquarius的最后一场匹配。 $1$2 表示匹配前后的数据。

    如果您使用变量进行替换,则需要使用双引号并转义 $ 以进行正则表达式替换,以便 PowerShell 不会尝试将它们视为变量

    $replace = "Bumblebee Joe"
    $text -replace "(.*)Aquarius(.*)", "`$1$replace`$2"
    

    【讨论】:

    • 它似乎只适用于替换字符串是文字。
    • 只有这种情况,因为它是用单引号括起来的。我可以更新答案来解决这个问题。
    • 嗯,由于某种原因,似乎不适用于多行字符串。它最终仍然替换了所有实例。
    • @sonjz 如果字符串是多行的,那么您可以使用单行模式。 "(?s)(.*)Aquarius(.*)", '$1Bumblebee Joe$2'
    • 感谢@Matt,快乐!我在使用 .NET .csproj 文件时遇到问题,现在可以使用,因为 csproj 很挑剔,所以分享我的解决方案: $file = Get-Content file.csproj -Raw ; $newFile = $file -replace "(?s)(.*)XXX(.*)", "$1$replaceVar$2" ; $新文件 | Out-File -Encoding UTF8 "new.csproj" ;
    【解决方案2】:

    Using the exact same technique as I would in C#:

    function Replace-LastSubstring {
        param(
            [string]$str,
            [string]$substr,
            [string]$newstr
        )
    
        return $str.Remove(($lastIndex = $str.LastIndexOf($substr)),$substr.Length).Insert($lastIndex,$newstr)
    }
    

    【讨论】:

    • 什么是$newstr?你不是只需要用户正在寻找的原始字符串和子字符串吗?
    • OP 需要 替换 子字符串,而不仅仅是删除它
    【解决方案3】:

    打印(str1[::-1].replace("xx","rr",1)[::-1])

    【讨论】:

      猜你喜欢
      • 2013-01-07
      • 1970-01-01
      • 2011-04-19
      • 2011-07-26
      • 2016-05-07
      • 2019-11-27
      • 2013-05-15
      相关资源
      最近更新 更多