regex: split by parentheses ignore nested parentheses inside quotes
java, regex
Solution
EDIT: After your comment about smilies, I'll suggest an alternative approach:
(?<=\()(?:'[^']*'|[,\s]+|\d+)+(?=\))
See demo. This assumes that your tokens are either strings delimited by single quotes, or digits. Is that correct?
Original Answer
With one potential level of nesting, this will work in most regex flavors, including Java:
(?<=\()(?:[^()]+|\([^)]+\))+
See demo
How does it work?
- The lookbehind asserts that the previous character is an opening parenthesis `(`
- The non-capturing group with the `+` quantifier matches one or more of: (i) any number of characters that are not opening or closing parentheses, OR `|` (ii) full `(parenthesized expressions)`
If you want to make sure that the container is balanced, add a lookahead at the end:
(?<=\()(?:[^()]+|\([^)]+\))+(?=\))
Problem
My program parses SQL VALUES multi-row string into single-row string array. Typical input string looks like: ``` (11,'-1','Service A (nested parentheses)','en') (22,'-2','Service B (nested parentheses)','en') ``` Desired output: - group 1: `11,'-1','Service A (nested parentheses)','en'` - group 2: `22,'-2','Service B (nested parentheses)','en'` I have tried following regexp, with partial luck only: ``` \(('.*?'|.*?)\) ``` What would be the right way to handle this in regexp? EDIT: - Target platform is Java 6/7 - There is no need in replacing the parentheses with new line - only to capture the groups