找到与Java regex matcher的最后一场比赛 [英] Find the last match with Java regex matcher
本文介绍了找到与Java regex matcher的最后一场比赛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图获得匹配的最后结果,而不必循环通过.find()
I'm trying to get the last result of a match without having to cycle through .find()
这是我的代码:
String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("num '([0-9]+) ");
Matcher m = p.matcher(in);
if (m.find()) {
in = m.group(1);
}
这将给我第一个结果。我如何找到最后一场比赛,而不是通过潜在的巨大名单?
That will give me the first result. How do I find the LAST match without cycling through a potentionally huge list?
推荐答案
你可以预先加上。 *
来您正则表达式,其将贪婪地消耗所有字符直到最后一场比赛:
You could prepend .*
to your regex, which will greedily consume all characters up to the last match:
import java.util.regex.*;
class Test {
public static void main (String[] args) {
String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile(".*num ([0-9]+)");
Matcher m = p.matcher(in);
if(m.find()) {
System.out.println(m.group(1));
}
}
}
打印:
2134
您也可以反转字符串以及更改正则表达式以匹配反向字符串:
You could also reverse the string as well as change your regex to match the reverse instead:
import java.util.regex.*;
class Test {
public static void main (String[] args) {
String in = "num 123 num 1 num 698 num 19238 num 2134";
Pattern p = Pattern.compile("([0-9]+) mun");
Matcher m = p.matcher(new StringBuilder(in).reverse());
if(m.find()) {
System.out.println(new StringBuilder(m.group(1)).reverse());
}
}
}
但两种解决方案都不比只需使用循环所有匹配,而(m.find())
,IMO。
But neither solution is better than just looping through all matches using while (m.find())
, IMO.
这篇关于找到与Java regex matcher的最后一场比赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文