Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split character string by forward slash or nothing

Tags:

regex

split

r

I want to split this vector

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

to

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

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

My final data should look like:

c("C_C", "C_C")

Thus, I need some regex, but don't found how to solve the "non-space" part:

strsplit(c("CC", "C/C"),"|/")
like image 210
Roman Avatar asked Dec 19 '17 09:12

Roman


1 Answers

You can use sub (or gsub if it occurs more than once in your string) to directly replace either nothing or a forward slash with an underscore (capturing one character words around):

sub("(\\w)(|/)(\\w)", "\\1_\\3", c("CC", "C/C"))
#[1] "C_C" "C_C"
like image 79
Cath Avatar answered Oct 02 '22 04:10

Cath