我有這段代碼,我想找到1234和4321,但目前我只能得到4321.我該如何解決這個問題?如何在正則表達式中使用組在java中?
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));
}
你的正則表達式應該是'坦率。*? ([0-9] *)坦率地說,否則,'。*'會吃掉所有東西。 – nhahtdh
瞭解[懶惰vs貪婪](http://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions)量詞。 –
要詳細說明@nhahtdh說的是什麼,默認情況下'*'是貪婪的,這意味着它會匹配儘可能大的數量。給它添加一個'?'使其不貪婪。 –