This problem had another solution that wasn't mentioned, so I'll post it here for completion. This situation is similar to this question to ["regex-match a pattern, excluding..."][4]
We can solve this with a beautifully-simple regex:
\([^)]*\)|(\s*,\s*)
The left side of the alternation |
matches complete (parentheses)
. We will ignore these matches. The right side matches and captures commas and surrounding spaces to Group 1, and we know they are the right apostrophes because they were not matched by the expression on the left. We will replace these commas by something distinctive, then split.
This program shows how to use the regex (see the results at the bottom of the online demo):
import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.util.List;
class Program {
public static void main (String[] args) throws java.lang.Exception {
String subject = "a, b, c, search:(1, 2, 3), d";
Pattern regex = Pattern.compile("\\([^)]*\\)|(\\s*,\\s*)");
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
if(m.group(1) != null) m.appendReplacement(b, "SplitHere");
else m.appendReplacement(b, m.group(0));
}
m.appendTail(b);
String replaced = b.toString();
String[] splits = replaced.split("SplitHere");
for (String split : splits) System.out.println(split);
} // end main
} // end Program
Reference
How to match (or replace) a pattern except in situations s1, s2, s3...