替换字符串中最后一次出现的子字符串 [英] Replacing last occurrence of substring in string

查看:71
本文介绍了替换字符串中最后一次出现的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can you replace the last occurrence of a substring in a string?

推荐答案

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

Regular Expressions can also perform this task. Here is an example of one that would work. It will replace the last occurrence of "Aquarius" with "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

贪婪量词确保它尽其所能,直到 Aquarius 的最后一场比赛.$1$2 代表匹配前后的数据.

The greedy quantifier ensure that it take everything it can up until the last match of Aquarius. The $1 and $2 represent the data before and after that match.

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

If you are using a variable for the replacement you need to use double quotes and escape the $ for the regex replacements so PowerShell does not try to treat them as a variable

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

这篇关于替换字符串中最后一次出现的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆