删除以“@”开头的术语,但如果它们在句子的开头

Delete the terms that begin with `@` but iff they are at the beginning of the sentence

我有三句话:

 x<-c("Hello @Ada how are you?","@Jack the weather is good", "Jack the weather is good")

我想删除以 @ 开头的术语,但前提是它们在句子的开头。例如,想要的结果是:

"Hello @Ada how are you?"  "the weather is good" "Jack the weather is good"

使用我的代码,相反,我得到了不同的结果:

>gsub("^@", "", x)
[1] "Hello @Ada how are you?"  "Jack the weather is good" "Jack the weather is good"

您可以添加[^ ]* *。其中 [^ ]* 是一切,但不是 space。

gsub("^@[^ ]* *", "", x)
#[1] "Hello @Ada how are you?"  "the weather is good"     
#[3] "Jack the weather is good"

您可以使用:

sub('^@\w+\s*', '', x)
#[1] "Hello @Ada how are you?"  "the weather is good"      "Jack the weather is good"

这将删除以 '@' 开头的第一个单词及其后面的空格。

包含元字符 ^ 以标记字符串中的第一个位置以及 trimws 以删除不需要的空格:

trimws(sub("^@\w+", "", x))
[1] "Hello @Ada how are you?"  "the weather is good" "Jack the weather is good"

这将替换以 @ 开头的第一个单词,直到第一个 space

> gsub("^@.*?\ ", "", x)
[1] "Hello @Ada how are you?"  "the weather is good"      "Jack the weather is good"