Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the last occurence of a string (and only it) using regular expression

Tags:

regex

r

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?

like image 702
Rtist Avatar asked Sep 08 '17 08:09

Rtist


1 Answers

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"
like image 66
akrun Avatar answered Oct 25 '22 00:10

akrun