Reputation: 401
I have to extract parts of a string in R based on a symbol and a word. I have a name such as
s <-"++can+you+please-help +me"
and the output would be:
"+ can" "+you" "+please" "-help" "+me"
where all words with the corresponding symbol before are shown. I've tried to use the strsplit and sub functions but I´m struggling in getting the output that I want. Can you please help me? Thanks!
Upvotes: 2
Views: 392
Reputation: 887078
Here is one option using base R
regmatches(s, gregexpr("[[:punct:]]\\w+", s))[[1]]
#[1] "+can" "+you" "+please" "-help" "+me"
Upvotes: 1
Reputation: 9313
Do
library(stringi)
result = unlist(stri_match_all(regex = "\\W\\w+",str = s))
Result
> result
[1] "+can" "+you" "+please" "-help" "+me"
No symbols
If you only want the words (no symbols), do:
result = unlist(stri_match_all(regex = "\\w+",str = s))
result
[1] "can" "you" "please" "help" "me"
Upvotes: 1