Oleg Bondar
Oleg Bondar

Reputation: 55

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") ?

Upvotes: 1

Views: 91

Answers (2)

Giorgi Chighladze
Giorgi Chighladze

Reputation: 130

You can also use stri_replace_last_regex from stringi package.

stringi::stri_replace_last_regex(str1, ";", "\t")

Upvotes: 0

akrun
akrun

Reputation: 887028

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")

Upvotes: 5

Related Questions