Matching Commas Outside Parentheses Using Regular Expressions
Problem:
Consider a string containing multiple commas, such as "12,44,foo,bar,(23,45,200),6." The goal is to create a regular expression in Java that matches all commas except those enclosed within parentheses, i.e., only the commas after 23 and 45 in the given example.
Solution:
To achieve this, we need to use a regular expression that incorporates a negative lookahead assertion. Here's a Java regular expression that satisfies this requirement:
Pattern regex = Pattern.compile( ", # Match a comma\n" + "(?! # only if it's not followed by...\n" + " [^(]* # any number of characters except opening parens\n" + " \) # followed by a closing parens\n" + ") # End of lookahead", Pattern.COMMENTS);
Explanation:
The above is the detailed content of How to Match Commas Outside Parentheses Using Regular Expressions in Java?. For more information, please follow other related articles on the PHP Chinese website!