【发布时间】:2021-06-07 21:21:24
【问题描述】:
如何替换字符串中最后次出现的子字符串?
【问题讨论】:
标签: powershell replace
如何替换字符串中最后次出现的子字符串?
【问题讨论】:
标签: powershell replace
正则表达式也可以执行此任务。这是一个可行的示例。它将用“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"
【讨论】:
"(?s)(.*)Aquarius(.*)", '$1Bumblebee Joe$2'
$1$replaceVar$2" ; $新文件 | Out-File -Encoding UTF8 "new.csproj" ;
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?你不是只需要用户正在寻找的原始字符串和子字符串吗?
打印(str1[::-1].replace("xx","rr",1)[::-1])
【讨论】: