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

How to Match Commas Outside Parentheses Using Regular Expressions in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 09:51:02247browse

How to Match Commas Outside Parentheses Using Regular Expressions in Java?

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:

  1. Comma Match: The first part of the regex, "commas", simply matches a comma.
  2. Negative Lookahead Assertion: The negative lookahead assertion, enclosed within the "(?!)" section, checks whether the following pattern does not match the comma.
  3. Nested Parentheses Check: This pattern consists of "1 )". The "1" part matches any number of characters except an opening parenthesis "(". The ")" part matches a closing parenthesis ")".
  4. Overall Logic: The negative lookahead ensures that the comma is only matched if it is not followed by any characters except opening parentheses, which are then followed by a closing parenthesis. This effectively excludes commas within parentheses.

  1. (

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!

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