Reputation: 4205
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?
Upvotes: 17
Views: 9171
Reputation: 954
While akrun's answer should solve the problem (not sure, haven't worked with \1
etc. yet), you can also use lookouts:
a(?!(.|\n)*a)
This is basically saying: Find an a
that is NOT followed by any number of characters and an a
. The (?!x)
is a so-called lookout, which means that the searched expression won't be included in the match.
You need (.|\n)
since .
refers to all characters, except for line breaks.
For reference about lookouts or other regex, I can recommend http://regexr.com/.
Upvotes: 4
Reputation: 51582
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"
Upvotes: 15
Reputation: 887028
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"
Upvotes: 14