How to split on / but not on // in R?

Viewed 91

Say i have this string:

str <- "a//b/c"

Desired Output:

c("a//b", "c").

So i want to split on /, but not on //.

What i tried:

Following https://stackoverflow.com/a/7317087/8538074 i tried:

  strsplit(split = "[[]^//[]]|/", x = "a//b/c", perl = TRUE)

(For non R-user: One Needs to escape Special characters in R, so "[" becomes "[[]", not sure this is common in all other languages.)

2 Answers

You may use

strsplit("a//b/c", "(?<!/)/(?!/)", perl=TRUE)

See the R demo online and the regex demo.

The (?<!/)/(?!/) pattern means:

  • (?<!/) - a location that is not immediately preceded with /
  • / - a / char
  • (?!/) - a location that is not immediately followed with /

We can also SKIP the pattern and match otherss

strsplit(str, "//(*SKIP)(*F)|/", perl = TRUE)[[1]]
#[1] "a//b" "c"   
Related