我有一个像这样的字符串: “我12岁,我想要15个等等。” 我想在java中使用正则表达式仅提取最后一个数字实例,我可以像这样提取所有数字:
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(msg);
if (m.find()) {
System.out.print("Start index: " + m.start());
System.out.print(" End index: " + m.end());
System.out.println(" Found: " + m.group());
}
,最后一个间隔就是它,但必须有简单的方法,这是否与$有关?
答案 0 :(得分:5)
答案 1 :(得分:1)
使用列表并获取最后一个元素
System.out.println("// TODO Auto-generated method stub");
String msg = "ich hebe 2 LBRs but i need 14 blah blah";
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(msg);
List<String> allNumericMatches = new ArrayList<String>();
while(m.find()) {
System.out.print("Start index: " + m.start());
System.out.print(" End index: " + m.end());
System.out.println(" Found: " + m.group());
allNumericMatches.add(m.group());
}
System.out.println(allNumericMatches.get(allNumericMatches.size()-1));