我正在尝试获得比赛的最后结果,而不必遍历.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);
}
这将给我第一个结果。我如何找到最后一个匹配,而不是循环通过一个潜在的巨大的列表?
发布于 2011-06-21 05:11:15
您可以将.*
添加到正则表达式中,这将greedily使用直到最后一个匹配的所有字符:
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
您还可以反转字符串,并更改正则表达式以匹配相反的字符串:
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());
}
}
}
但是,这两种解决方案都比使用while (m.find())
、IMO在所有比赛中循环更好。
发布于 2013-04-25 07:08:01
为了获得最后一次匹配,即使这样也可以,但不确定为什么之前没有提到:
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(m.groupCount());
}
发布于 2011-06-21 05:40:25
为什么不保持简单呢?
in.replaceAll(".*[^\\d](\\d+).*", "$1")
https://stackoverflow.com/questions/6417435
复制相似问题