Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last comma in character with " &"

I have many different characters which have the following structure:

# Example
x <- "char1, char2, char3"

I want to remove the last comma of this character with " &", i.e. the desired output should look as follows:

# Desired output
"char1, char2 & char3"

How could I replace the last comma of a character with " &"?

like image 521
Joachim Schork Avatar asked Feb 07 '19 16:02

Joachim Schork


2 Answers

You can use sub :

sub(",([^,]*)$"," &\\1", x)
# [1] "char1, char2 & char3"
like image 103
Moody_Mudskipper Avatar answered Sep 19 '22 19:09

Moody_Mudskipper


One option is stri_replace_last from stringi

library(stringi)
stri_replace_last(x, fixed = ',', ' &')
#[1] "char1, char2 & char3"
like image 24
akrun Avatar answered Sep 19 '22 19:09

akrun