Tonja Tonja - 10 months ago 67
R Question

R: gsub punctuation characters only at the end of the string

I have string like 'aa;a' 'aa;' and I need to delete ';' (or any other punctuation character) only if the string ends with it. If it starts with it or contains it in the middle, I do not want to delete it.

The below line results in the deleting of the ';'


Answer Source

We can specify the metacharacter $ after the [[:punct:]] to signify the end of the string, thus it matches a punctuation at the end of the string and replace it with blank ("")

sub("[[:punct:]]$","",c('a;a', 'aa;'))
#[1] "a;a" "aa" 

Note that instead of gsub (global substitution), the sub is used to match and replace only for a single instance.