Home  >  Article  >  Java  >  How to Match Commas Outside Parentheses in Java Using Regex?

How to Match Commas Outside Parentheses in Java Using Regex?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 21:15:02428browse

How to Match Commas Outside Parentheses in Java Using Regex?

Matching Commas Outside Parentheses in Strings

Consider a string resembling the following:

The goal is to construct a regex in Java to select only the commas that are not enclosed within parentheses. In this example, the desired matches would be the commas following "12" and "44."

Solution

The following Java regex accomplishes the task:

Explanation

This regex utilizes a negative lookahead assertion, represented by "(?!...)," to ensure that the next following parenthesis (if any) is not a closing parenthesis. This constraint allows the comma to match only when it is not located within a parenthetical expression.

The above is the detailed content of How to Match Commas Outside Parentheses in Java Using Regex?. 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