使用正则表达式替换字符串的最后一次出现(并且仅替换它) [英] Replace the last occurence of a string (and only it) using regular expression
问题描述
我有一个字符串,比如说 MyString = "aabbccawww".我想使用 gsub 表达式将 MyString 中的最后一个a"替换为A",并且只有它.那就是aabbccAwww".我在网站上发现了类似的问题,但他们都要求替换最后一次出现的和之后出现的所有问题.我试过 gsub("a[^a]*$", "A", MyString),但它给出了 "aabbccA".我知道我可以为此目的使用 stringi 函数,但我需要在代码的一部分中实现解决方案,使用这些函数会很复杂,所以我想使用正则表达式.有什么建议吗?
I have a string, let say MyString = "aabbccawww". I would like to use a gsub expression to replace the last "a" in MyString by "A", and only it. That is "aabbccAwww". I have found similar questions on the website, but they all requested to replace the last occurrence and everything coming after. I have tried gsub("a[^a]*$", "A", MyString), but it gives "aabbccA". I know that I can use stringi functions for that purpose but I need the solution to be implemented in a part of a code where using such functions would be complicated, so I would like to use a regular expression. Any suggestion?
推荐答案
你可以使用 stringi
库,它使处理字符串变得非常容易,即
You can use stringi
library which makes dealing with strings very easy, i.e.
library(stringi)
x <- "aabbccawww"
stri_replace_last_fixed(x, 'a', 'A')
#[1] "aabbccAwww"
这篇关于使用正则表达式替换字符串的最后一次出现(并且仅替换它)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!