Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...