Tonja Tonja - 1 year ago 84
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download