替换字符串中最后一次出现的子字符串

Replacing last occurrence of substring in string

如何替换字符串中出现的 last 个子字符串?

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)
}

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

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

贪心量词确保它尽可能地获取所有内容,直到 Aquarius 的最后一场比赛。 </code> 和 <code> 表示匹配前后的数据。

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

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

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