我有很多带有特殊符号的字符串,例如"〜"然后是拉丁字母,然后是空格" ":
x <- c('~yesicametoyour home tonight.', 'yes~iknow this fact for sure,')
1)〜今晚回家了。
2)是的〜我确实知道这个事实,
我想删除这个&#34;〜&#34;之间的任何字符。以及在该角色之后存在的第一个空格。
结果必须是
1)今晚回家。
2)肯定是这个事实,
gsub( "(@.*[[:space:]]),", "aaaaaaaaaa", df5)
答案 0 :(得分:0)
您希望匹配~
,然后匹配除空白(\S+
)以外的任何一个或多个字符。
模式清晰:~\S+
。请参阅the regex demo at regex101.com。
在R中,您可以使用
> trimws(gsub("~\\S+", "", x))
[1] "home tonight." "yes this fact for sure,"
trimws
将删除删除后剩余的任何前导或尾随空格。
答案 1 :(得分:0)
以下是仅使用gsub
的选项(手动执行trimws
的效果)。
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,"