Split character string using slash or nothing

I want to smash this vector

c("CC", "C/C") 

to

 [[1]] [1] "C" "C" [[2]] [1] "C" "C" 

My final data should look like this:

 c("C_C", "C_C") 

Thus, I need a little regex , but not find how to solve the "non-space" part:

 strsplit(c("CC", "C/C"),"|/") 
+7
split regex r
source share
3 answers

You can use sub (or gsub if it occurs more than once on your line) to directly replace anything or a slash with an underscore (capturing one character word):

 sub("(\\w)(|/)(\\w)", "\\1_\\3", c("CC", "C/C")) #[1] "C_C" "C_C" 
+8
source share

We can use

 lapply(strsplit(v1, "/|"), function(x) x[nzchar(x)]) 

Or use regex

 strsplit(v1, "(?<=[^/])(/|)", perl = TRUE) #[[1]] #[1] "C" "C" #[[2]] #[1] "C" "C" 

If the final result should be a vector, then

 gsub("(?<=[^/])(/|)(?=[^/])", "_", v1, perl = TRUE) #[1] "C_C" "C_C" 
+5
source share

We can split the line into each character, omit the "/" and paste together between them.

 sapply(strsplit(x, ""), function(v) paste0(v[v!= "/"], collapse = "_")) #[1] "C_C" "C_C" 

<strong> data

 x <- c("CC", "C/C") 
+5
source share

All Articles