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 ';'
gsub("(^.*)[[:punct:]]","",'a;a')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With