使用regex或sub如何删除句子中任何字符和空格之间的任何字符串?

使用regex或sub如何删除句子中任何字符和空格之间的任何字符串?,regex,r,whitespace,Regex,R,Whitespace,我有很多字符串都有一个特殊的符号,例如“~”,后跟拉丁字母,然后是空格“”: 您希望匹配~,然后匹配除空格以外的任何一个或多个字符(\s+) 模式很清楚:~\S+。看 在R中,您可以使用 > trimws(gsub("~\\S+", "", x)) [1] "home tonight." "yes this fact for sure," trimws将删除删除后剩余的任何前导或尾随空格。这里有一个选项,仅使用gsub(手动执行trimws的效果) xtrimws(g

我有很多字符串都有一个特殊的符号,例如“~”,后跟拉丁字母,然后是空格“”:


您希望匹配
~
,然后匹配除空格以外的任何一个或多个字符(
\s+

模式很清楚:
~\S+
。看

在R中,您可以使用

> trimws(gsub("~\\S+", "", x))
[1] "home tonight."           "yes this fact for sure,"

trimws
将删除删除后剩余的任何前导或尾随空格。

这里有一个选项,仅使用
gsub
(手动执行
trimws
的效果)

x
trimws(gsub(“~\\w+”,“”,x))
gsub(“^~\\w+| ~\\w+”,“”,x)
gsub( "(@.*[[:space:]]),", "aaaaaaaaaa", df5)
> trimws(gsub("~\\S+", "", x))
[1] "home tonight."           "yes this fact for sure,"
x <- c('~yesicametoyour home tonight.', 'yes~iknow this fact for sure,')

gsub("(^ | $)", "",      ## (2) replace a space at the start or end with nothing
  gsub("~[^ ]*", "", x)  ## (1) replace pattern ~[everything up to a space] with nothing
)
[1] "home tonight."           "yes this fact for sure,"