首页 > 解决方案 > 从句子中删除单个字符

问题描述

我是字符串来清理一些包含单个字符的句子,例如:

sentence <- c('this is a z test', 'remove this b from here')

我想 从句子中删除zand以拥有:b

c('this is a test', 'remove this from here')

我尝试过这样的事情:

gsub('"([\\b[a-zA-Z0-9]{1,1}\\b])"', '', sentence)

但它不工作。

标签: r

解决方案


我们可以使用gsubwith word boundary ( \\b)

gsub("\\s\\b[zb]\\b", "", sentence)
#[1] "this is a test"        "remove this from here"

如果要删除“a”或“i”以外的值,请^在方括号内指定

gsub("\\s\\b[^ai]\\b", "", sentence)

推荐阅读