Search code examples
rstringstrsplit

RegEx for matching all commas unless they are enclosed between parentheses or brackets


Consider the following code in R:

x <- "A, B (C, D, E), F, G [H, I, J], K (L (M, N), O), P (Q (R, S (T, U)))"
strsplit(x, split = "some regex here")

I would like this to return something resembling a list containing the character vector

"A"
"B (C, D, E)"
"F"
"G [H, I, J]"
"K (L (M, N), O)"
"P (Q (R, S (T, U)))"

EDIT: The proposed alternative questions do not answer my question, since nested parentheses and brackets are allowed, and it is possible for n-level nesting to occur (beyond 2).


Solution

  • This looks more like a job for a custom parser than a single regex. I would love to be proved wrong, but while we're waiting, here's a very pedestrian parsing function that gets the job done.

    parse_nested <- function(string) {
      
      chars <- strsplit(string, "")[[1]]
      
      parentheses <- numeric(length(chars))
      parentheses[chars == "("] <- 1
      parentheses[chars == ")"] <- -1
      parentheses <- cumsum(parentheses)
    
      brackets <- numeric(length(chars))
      brackets[chars == "["] <- 1
      brackets[chars == "]"] <- -1
      brackets <- cumsum(brackets)
      
      split_on <- which(brackets == 0 & parentheses == 0 & chars == ",")
      split_on <- c(0, split_on, length(chars) + 1)
      
      result <- character()
      
      for(i in seq_along(head(split_on, -1))) {
        x <- paste0(chars[(split_on[i] + 1):(split_on[i + 1] - 1)], collapse = "")
        result <- c(result, x)
      }
      
      trimws(result)
    }
    

    Which produces:

    parse_nested(x)
    #> [1] "A"                   "B (C, D, E)"         "F"                  
    #> [4] "G [H, I, J]"         "K (L (M, N), O)"     "P (Q (R, S (T, U)))"