4

I am currently trying to split a string on the pipe delimiter: 

999|150|222|(123|145)|456|12,260|(10|10000)

The catch is I don't want to split on | inside of parentheses, I only want to split on this character outside of parentheses.

This is just splitting on every | character, yielding the results I don't want:

x <- '999|150|222|(123|145)|456|12,260|(10|10000)'
m <- strsplit(x, '\\|')

[[1]]
[1] "999"    "150"    "222"    "(123"   "145)"   "456"    "12,260" "(10"   
[9] "10000)"

I am looking to get the following results keeping everything inside of parentheses:

[[1]]
[1] "999"        "150"        "222"        "(123|145)"  "456"       
[6] "12,260"     "(10|10000)"

Any help appreciated.

hwnd
  • 69,796
  • 4
  • 95
  • 132
user3856888
  • 229
  • 1
  • 7

3 Answers3

12

You can switch on PCRE by using perl=T and some dark magic:

x <- '999|150|222|(123|145)|456|12,260|(10|10000)'
strsplit(x, '\\([^)]*\\)(*SKIP)(*F)|\\|', perl=T)

# [[1]]
# [1] "999"        "150"        "222"        "(123|145)"  "456"       
# [6] "12,260"     "(10|10000)"

The idea is to skip content in parentheses. Live demo

On the left side of the alternation operator we match anything in parentheses making the subpattern fail and force the regular expression engine to not retry the substring using backtracking control. The right side of the alternation operator matches | (outside of parentheses, what we want...)

hwnd
  • 69,796
  • 4
  • 95
  • 132
6

One option:

scan(text=gsub("\\(|\\)", "'", x), what='', sep="|")
#[1] "999"      "150"      "222"      "123|145"  "456"      "12,260"   "10|10000"

Here's another way using strsplit. There are other answers here using strsplit, but this seems to be the simplest pattern that works:

strsplit(x, "\\|(?!\\d+\\))", perl=TRUE)
# [1] "999"        "150"        "222"        "(123|145)"  "456"        "12,260"     "(10|10000)"
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
3

This seems to work

x <- '999|150|222|(123|145)|456|12,260|(10|10000)'
m <- strsplit(x, '\\|(?=[^)]+(\\||$))', perl=T)

# [[1]]
# [1] "999"        "150"        "222"        "(123|145)"  "456"        "12,260"    
# [7] "(10|10000)"

Here we not just split on the | but we also use a look ahead to make sure that there are no ")" marks before the next | or the end of the string. Note that this method doesn't require or ensure the parenthesis are balanced and closed. We assume your input is well formatted.

MrFlick
  • 195,160
  • 17
  • 277
  • 295