ACLAN
ACLAN

Reputation: 401

Split a string by a sign and word

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

Answers (2)

akrun
akrun

Reputation: 887078

Here is one option using base R

regmatches(s, gregexpr("[[:punct:]]\\w+", s))[[1]]  
#[1] "+can"    "+you"    "+please" "-help"   "+me"    

Upvotes: 1

R. Schifini
R. Schifini

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

Related Questions