正则表达式只匹配逗号不在括号中? [英] Regex to match only commas not in parentheses?

查看:164
本文介绍了正则表达式只匹配逗号不在括号中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下内容的字符串:

I have a string that looks something like the following:

12,44,foo,bar,(23,45,200),6

我想创建一个与逗号匹配的正则表达式,但只有逗号不在括号内(在上面的例子中,除了23和45之后的两个逗号之外的所有逗号)。我该怎么做(Java正则表达式,如果这有所不同)?

I'd like to create a regex that matches the commas, but only the commas that are not inside of parentheses (in the example above, all of the commas except for the two after 23 and 45). How would I do this (Java regular expressions, if that makes a difference)?

推荐答案

假设没有嵌套的parens (否则,您不能使用Java Regex执行此任务,因为不支持递归匹配):

Assuming that there can be no nested parens (otherwise, you can't use a Java Regex for this task because recursive matching is not supported):

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);

此正则表达式使用否定先行断言,以确保下一个括号(如果有)不是右括号。只有这样才能使逗号匹配。

This regex uses a negative lookahead assertion to ensure that the next following parenthesis (if any) is not a closing parenthesis. Only then the comma is allowed to match.

这篇关于正则表达式只匹配逗号不在括号中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆