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

nic*_*ckm 3 powershell replace

如何替换字符串中最后一个子字符串?

Mat*_*att 10

正则表达式也可以执行此任务.这是一个可行的例子.它将用"Bumblebee Joe"取代最后一次出现的"水瓶座"

$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
Run Code Online (Sandbox Code Playgroud)

贪婪的量词确保它可以在最后一场比赛之前完成所有工作Aquarius.在$1$2前和比赛后表示数据.

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

$replace = "Bumblebee Joe"
$text -replace "(.*)Aquarius(.*)", "`$1$replace`$2"
Run Code Online (Sandbox Code Playgroud)


Mat*_*sen 5

使用与我在中使用的完全相同的技术C#

function Replace-LastSubstring {
    param(
        [string]$str,
        [string]$substr,
        [string]$newstr
    )

    return $str.Remove(($lastIndex = $str.LastIndexOf($substr)),$substr.Length).Insert($lastIndex,$newstr)
}
Run Code Online (Sandbox Code Playgroud)