3

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.)

Tlatwork
  • 1,445
  • 12
  • 35

2 Answers2

5

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 /
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
3

We can also SKIP the pattern and match otherss

strsplit(str, "//(*SKIP)(*F)|/", perl = TRUE)[[1]]
#[1] "a//b" "c"   
akrun
  • 874,273
  • 37
  • 540
  • 662