Home > Mobile >  How to split a string in multiple part using first bracket in R?
How to split a string in multiple part using first bracket in R?

Time:09-27

I have strings like -

st1<- c("realme C20 (Cool Blue, 32 GB)")
st2<- c("realme C11 (2021) (Cool Grey, 2GB RAM, 32GB Storage)")

and I want to split s.t. I get my output as -

output1
[1] "realme C20"       "Cool Blue, 32 GB" "NA"
output2
[1] "realme C11"       "2021"             "Cool Grey, 2GB RAM, 32GB Storage"

I have no idea at all about how to proceed.

CodePudding user response:

regex is my weak point, but maybe this helps you:

library(stringr)
library(dplyr)


str_split(st1,"\\(|\\)") %>% unlist()
[1] "realme C20 "      "Cool Blue, 32 GB" ""                

str_split(st2,"\\(|\\)") %>% unlist()
[1] "realme C11 "                      "2021"                            
[3] " "                                "Cool Grey, 2GB RAM, 32GB Storage"
[5] ""

If "" do not matter, you can remove them also

  • Related