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

Viewed 37

I have three sentences:

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

I would like to delete the terms that begin with @ but iff they are at the beginning of the sentence. For example, the desired result is:

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

Wih my code, instead, I obtained a different result:

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

You can to add [^ ]* *. Where [^ ]* is everything but not a space.

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

You could use :

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

This deletes the first word that start with '@' along with the whitespace following it.

This will replace first word starting with @ upto the first space

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

Include the metacharacter ^ to mark the first position in the string as well as trimwsto remove unwanted whitespace:

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