Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

Java regex: Repeating capturing groups

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

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

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

Tips? Thanks

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Related question:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...