Home > OS >  Split a string and keep delimiter
Split a string and keep delimiter

Time:11-03

Lets say I have a string:

StringA/StringB/StringC

Is there any way I can split this string by the / symbol, but keep it in the returned values:

StringA
/StringB
/StringC

CodePudding user response:

Yes, with a look-ahead: (?=/)

library(stringr)
str_split(str, "(?=/)")

#[[1]]
#[1] "StringA"  "/StringB" "/StringC"

Works equally well with tidyr separating function:

tidyr::separate_rows(data.frame(str), str, sep = "(?=/)")

#  str        
#1 StringA 
#2 /StringB
#3 /StringC

With base R's strsplit, look-aheads are less straightforwards, but this works well:

unlist(strsplit(str, "(?<=.)(?=[/])", perl = TRUE))
#[1] "StringA"  "/StringB" "/StringC"

And reversely:

unlist(strsplit(str, "(?<=/)", perl = TRUE))
#[1] "StringA/" "StringB/" "StringC" 

CodePudding user response:

You can try scan gsub like below

> scan(text = gsub("/", " /", "StringA/StringB/StringC"), what = "")
Read 3 items
[1] "StringA"  "/StringB" "/StringC"

CodePudding user response:

With str_extract

library(stringr)
str_extract_all(str1, "/?[^/] ")[[1]]
[1] "StringA"  "/StringB" "/StringC"
  • Related