R: gsub 标点字符只出现在字符串的末尾

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

我有像 'aa;a' 'aa;' 这样的字符串,我需要删除 ';' (或任何其他标点符号)仅当字符串以它结尾时。如果以它开头或中间包含它,我不想删除它。

下一行导致删除“;”

gsub("(^.*)[[:punct:]]","",'a;a')

我们可以在[[:punct:]]后面指定元字符$来表示字符串的结束,这样就匹配了字符串末尾的一个标点符号,将其替换为空格("")

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

请注意 gsub(全局替换),sub 用于匹配和替换单个实例。