如何替换最后字符串中出现的子字符串?替换字符串中最后出现的子字符串
2
A
回答
5
正则表达式也可以执行此任务。这是一个可以工作的例子。它将与“大黄蜂乔”
$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"
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)
}
+0
是什么'$ newstr'更换一个变量?你不只需要用户正在寻找的原始字符串和子字符串? – 2017-11-07 00:19:05
+0
OP需要*替换*子字符串,而不仅仅是删除它 – 2017-11-07 08:29:31
相关问题
- 1. 替换字符串中最后一次出现的字符
- 2. Javascript/jQuery - 替换字符串中最后一个字的出现
- 3. 第一次替换字符串中出现的字符串VB.NET
- 4. 替换字符串中最后一次出现的单词 - c#
- 5. 的JavaScript:替换字符串文本中最后一次出现
- 6. 用替换字符串中出现的相同单词替换字符串
- 7. 用包含原始子字符串的条件子字符串替换多个出现的子字符串
- 8. 字符串中的字符串替换
- 9. 如何替换在字符串中多次出现的子字符串?
- 10. 如何查找Swift字符串中子字符串的最后一次出现?
- 11. 替换所有出现的字符串
- 12. CFAttributedString替换字符串的出现?
- 13. 替换所有的字符串出现
- 14. 替换字符串中的最后一个字符
- 15. 替换Groovy中现有字符串中的字符串
- 16. MySQL替换出现在另一个字符串后面的字符串部分
- 17. Jquery子字符串替换
- 18. 替换字符串内的字符串
- 19. 如何替换字符串中的子字符串
- 20. 替换字符串中的多个子字符串
- 21. C#替换字符串中的匹配子字符串
- 22. 替换字符串中的子字符串
- 23. 替换字符串中的子字符串
- 24. 替换字符串中的多个子字符串
- 25. 用子串替换后续分隔符之间的字符串
- 26. PHP替换多行字符串中最后一次出现的字
- 27. 用jquery/regex替换子字符串中的最后一个匹配的字符
- 28. 查找字符串中字符的最后出现次数
- 29. 将字符串替换为字符串
- 30. 使用JavaScript替换字符串的最后一个字符
它似乎只适用于替换字符串是文字。 – nickm 2015-02-10 17:56:29
这是唯一的情况,因为它被括在单引号中。我可以更新答案来解释这一点。 – Matt 2015-02-10 18:05:45
现在它完美的工作。谢谢。 – nickm 2015-02-11 07:39:18