正则表达式:删除以字符开头和结尾的单词或字母

时间:2018-07-31 19:30:49

标签: r regex

我想使用Regex删除R中以特定字符开头和结尾的单词或字母。

例如

"I want to delete @word&"

应该是

 "I want to delete"

"I  want to delete @p&"

应该是

"I want to delete" 

2 个答案:

答案 0 :(得分:1)

您可以使用gsub

gsub("@[^&]*&","","I want to delete @word&")
# [1] "I want to delete "


gsub("(^|\\s)@[^&]*&","","I  want to delete @p&")
# [1] "I  want to delete "

处理多余空间的方式将取决于您的实际情况,但我认为,如果可以接受调整后的输出,则以下内容应该可以:

trimws(gsub("\\s*@[^&]*&","","@nope& hello @nope& world @nope&"))
# [1] "hello world"

答案 1 :(得分:0)

不同的模式-仅使+不贪心:

gsub("@.+?&","","I want to delete @word&")