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?
We can use sub
to match 'a' followed by zero or more characters that are not an 'a' ([^a]*
), capture it as group ((...)
) until the end of the string ($
) and replace it with "A" followed by the backreference of the captured group (\\1
)
sub("a([^a]*)$", "A\\1", MyString)
#[1] "aabbccAwww"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With