开发者

Regex static group problem

I have several strings in the rough form:

[some number with one or 2 digits] [some text] [a text which is ABC or BC] [some text]

String test = "12testABCtest";
Pattern p = Pattern.compile("([\\d]{1,2})([\\w]*)(ABC|BC)([\\w]*)");

But it gives me always "BC in the 3rd group instead of ABC. ( as it include the A in the previous group )

Do you have any idea how to do it?

th开发者_如何学编程ank you,


You can make the text match non-greedy:

Pattern p = Pattern.compile("([\\d]{1,2})([\\w]*?)(A?BC)([\\w]*)");

Reference:

Reluctant quantifiers
-----------------------------
X??     X, once or not at all
X*?     X, zero or more times
X+?     X, one or more times

Source: Pattern javadoc: Reluctant quantifiers

Basically: reluctant quantifiers will match as little as possible, as opposed to the default greedy quantifiers that will match as much as possible. You get a reluctant quantifier by appending a ? to another quantifier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜