Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Split String on Comma, Skip Anything Between Balanced Parentheses

Need to write a regex in R - Perl which would split string on comma ',' but skip all instances of comma in between round parenthesis. The challenge is to ensure that the parentheses are balanced, i.e. close bracket maps back to its open bracket.

In the below regex code, everything works perfectly, except if you notice - Parentheses are not balanced, an inner end bracket is being considered for an outer start bracket

text <- "PEANUTS (PEANUTS, PEANUT OIL AND/OR COTTONSEED OIL AND/OR CANOLA OIL AND/OR SOYBEAN OIL, SALT), GOLDEN RAISINS (RAISINS, SULFUR DIOXIDE), DRIED CRANBERRIES (CRANBERRIES, SUGAR, CITRIC ACID, SUNFLOWER OIL (PROCESSING AID), ELDERBERRY JUICE CONCENTRATE (COLOR)), ALMONDS (ALMONDS, PEANUT OIL AND/OR COTTONSEED OIL AND/OR CANOLA OIL AND/OR SOYBEAN OIL, SALT), MACADAMIAS (MACADAMIAS, MALTODEXTRIN, SALT)"

strsplit(text, '\\([^*)^)]*\\)(*SKIP)(*F)|\\,', perl=T)

Using the above regex code, Dried Cranberries is not being splitted correctly. Please refer to the output screenshot here: Regex Code Output

Any help here would be much appreciated.. Thank you!

like image 402
Mohit Gulla Avatar asked Sep 04 '26 15:09

Mohit Gulla


1 Answers

You may use

strsplit(text, "(\\((?:[^()]++|(?1))*\\))(*SKIP)(*F)|,", perl=TRUE)
# => [[1]]
[1] "PEANUTS (PEANUTS, PEANUT OIL AND/OR COTTONSEED OIL AND/OR CANOLA OIL AND/OR SOYBEAN OIL, SALT)"                            
[2] " GOLDEN RAISINS (RAISINS, SULFUR DIOXIDE)"                                                                                 
[3] " DRIED CRANBERRIES (CRANBERRIES, SUGAR, CITRIC ACID, SUNFLOWER OIL (PROCESSING AID), ELDERBERRY JUICE CONCENTRATE (COLOR))"
[4] " ALMONDS (ALMONDS, PEANUT OIL AND/OR COTTONSEED OIL AND/OR CANOLA OIL AND/OR SOYBEAN OIL, SALT)"                           
[5] " MACADAMIAS (MACADAMIAS, MALTODEXTRIN, SALT)" 

See the regex demo and an online R demo.

Details

  • (\\((?:[^()]++|(?1))*\\)) - a capturing group #1 that captures
    • \\( - a ( char
    • (?:[^()]++|(?1))* - 0 or more occurrences of 1+ chars other than ( and ) (with [^()]++) or (|) the whole group 1 pattern (that is recursed to match all nested levels)
    • \\) - a ) char
  • (*SKIP)(*F) - the two verbs make the engine skip the currently matched string and go on to look for the next match immediately after this text.
  • | - or
  • , - a comma.
like image 90
Wiktor Stribiżew Avatar answered Sep 07 '26 11:09

Wiktor Stribiżew