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

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

问题描述

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

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

推荐答案

假设不能有嵌套括号(否则你不能使用 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
" +
    "(?!       # only if it's not followed by...
" +
    " [^(]*    #   any number of characters except opening parens
" +
    " \)      #   followed by a closing parens
" +
    ")         # End of lookahead", 
    Pattern.COMMENTS);

此正则表达式使用 否定前瞻断言 来确保接下来的括号(如果any) 不是右括号.只有这样,逗号才允许匹配.

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天全站免登陆