简体   繁体   English

如何在正则表达式中使用组在java中?

[英]How to use groups in Regular Expression In java?

I have this code and I want to find both 1234 and 4321 but currently I can only get 4321. How could I fix this problem? 我有这个代码,我想找到1234和4321,但目前我只能得到4321.我怎么能解决这个问题?

String a = "frankabc123 1234 frankabc frankabc123 4321 frankabc";
String rgx = "frank.* ([0-9]*) frank.*";
Pattern patternObject = Pattern.compile(rgx);
Matcher matcherObject = patternObject.matcher(a);
while (matcherObject.find()) {
    System.out.println(matcherObject.group(1));
}

Your regex is too greedy. 你的正则表达式太贪心了。 Make it non-greedy. 让它不贪心。

String rgx = "frank.*? ([0-9]+) frank";

Your re is incorrect. 你的不正确。 The first part: frank.* matches everything and then backtracks until the rest of the match succeeds. 第一部分: frank.*匹配所有内容然后回溯直到比赛的其余部分成功。 Try this instead: 试试这个:

String rgx = "frank.*? ([0-9]*) frank";

The ? ? after the quantifier will make it reluctant, matching as few characters as necessary for the rest of the pattern to match. 在量词将使其不情愿之后,匹配尽可能少的字符以匹配模式的其余部分。 The trailing .* is also causing problems (as nhahtdh pointed out in a comment). 尾随.*也导致问题(正如nhahtdh在评论中指出的那样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM