Matching Commas Excluding Parenthetical Occurrences
Consider the following string:
12,44,foo,bar,(23,45,200),6
The task at hand is to devise a regular expression that specifically targets commas that lie outside of parentheses. In other words, in the provided example, we need a regex that matches the two commas after "23" and "45" but excludes the others.
Java Regular Expression Solution
Presuming nested parentheses are absent, we can employ the following Java regular expression to achieve the desired outcome:
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 of the Regex
This regex utilizes a negative lookahead assertion to confirm that any subsequent parenthesis (if encountered) is not a closing parenthesis. If this condition is met, the comma is recognized as a match.
The lookahead assertion operates as follows:
This ensures that the regex only matches commas that are not immediately followed by a closing parenthesis.
The above is the detailed content of How to Match Commas Outside Parentheses in Java?. For more information, please follow other related articles on the PHP Chinese website!