Java正则表达式:重复捕获组 [英] Java regex: Repeating capturing groups

查看:181
本文介绍了Java正则表达式:重复捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

项目是逗号分隔的一个或多个数字或字符串的列表,例如

An item is a comma delimited list of one or more strings of numbers or characters e.g.

"12"
"abc"
"12,abc,3"

我正在努力匹配Java中零个或多个项目的括号列表,例如

I'm trying to match a bracketed list of zero or more items in Java e.g.

""
"(12)"
"(abc,12)"
"(abc,12),(30,asdf)"
"(qqq,pp),(abc,12),(30,asdf,2),"

分别为最后一个示例返回以下匹配组

which should return the following matching groups respectively for the last example

qqq,pp
abc,12
30,asdf,2

我想出了以下(不正确)模式

I've come up with the following (incorrect)pattern

\((.+?)\)(?:,\((.+?)\))*

在最后一个例子中仅匹配以下内容

which matches only the following for the last example

qqq,pp
30,asdf,2

小贴士?谢谢

推荐答案

这是对的。您不能在Java正则表达式中拥有可变数量的捕获组。你的模式有两组:

That's right. You can't have a "variable" number of capturing groups in a Java regular expression. Your Pattern has two groups:

\((.+?)\)(?:,\((.+?)\))*
  |___|        |___|
 group 1      group 2

每组将包含最后一场比赛的内容为该组。即, abc,12 将被 30,asdf,2 覆盖。

Each group will contain the content of the last match for that group. I.e., abc,12 will get overridden by 30,asdf,2.

相关问题:

  • Regular expression with variable number of groups?

解决方案是使用一个表达式(类似 \((。+?)\))并使用 matcher.find 迭代匹配。

The solution is to use one expression (something like \((.+?)\)) and use matcher.find to iterate over the matches.

这篇关于Java正则表达式:重复捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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