POSIX character classes need to be wrapped inside of a bracketed expression, the correct syntax would be [[:punct:]]
. And, since you're not utilizing gsub
to remove all instances, you need to specify an operator to match more than one occurrence of punctuation.
As commented in the other answer; the perl = TRUE
parameter needs to be set to use \Z
.
But for future reference — not to dissuade you, this anchor behaves differently depending on the engine being used; being said in R with the parameter set, this anchor will allow a match before a final line break. However, it's alright to use it here, but I would just stick to $
instead.
sub('[[:punct:]]+$', '', c('fafasdf..', 'sdfs?>', 'safwe'))
## [1] "fafasdf" "sdfs" "safwe"
Also take into account the 'locale', it could affect the behavior of the POSIX class. If this becomes an issue, you can read up on this previously answered question.
If you're just wanting to removing non-word characters, you could just use:
sub('\\W+$', '', c('fafasdf..', 'sdfs?>', 'safwe'))
## [1] "fafasdf" "sdfs" "safwe"