Home >Java >javaTutorial >How to Match Commas Outside Parentheses in Java?

How to Match Commas Outside Parentheses in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 21:49:02328browse

How to Match Commas Outside Parentheses in Java?

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:

  • (?! initiates a negative lookahead assertion.
  • [^(]* indicates that the regex engine should look for any number of characters except opening parentheses.
  • \) specifies that a closing parenthesis should immediately follow the preceding characters.
  • ) concludes the lookahead assertion.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn