Search code examples
rstringcharacter

Replace first occurrence from the end of a string in R


As an example I have this vector

c("qw;erty;qwert;qwe;", "ty;qwert;qw")

How can I use sub function or any other to replace first occurrences of ";" from the end of the line with "\t" so the result will be c("qw;erty;qwert;qwe\t", "ty;qwert\tqw") ?


Solution

  • We can try

    sub(";([^;]*)$", "\t\\1", str1)
    #[1] "qw;erty;qwert;qwe\t" "ty;qwert\tqw"  
    

    data

    str1 <- c("qw;erty;qwert;qwe;", "ty;qwert;qw")