查找最后一个:
@Test
public void testFindFirstRegExp() {
String pattern = ".* (\\d+,\\d+) .*";
Pattern r = Pattern.compile(pattern);
String line = "some text 44,66 m² some 33,11 m² text 11,22 m² some text";
Matcher m = r.matcher(new StringBuilder(line).reverse().toString());
String expected = "44,66";
String actual = null;
if (m.find()) {
actual = new StringBuilder(m.group(1)).reverse().toString();
}
System.out.println("got first:" + actual);
Assert.assertEquals(expected, actual);
m = r.matcher(line);
expected = "11,22";
actual = null;
if (m.find()) {
actual = m.group(1);
}
System.out.println("got last:" + actual);
Assert.assertEquals(expected, actual);
}
打印:
got first:44,66
got last:11,22
注意:需要时请反转模式,例如:
pattern = ".* (\\d+,\\d+-?) .*"; //reverse for (-?\\d+,\\d+)
但这将按预期工作:
pattern = " (\\-?\\d+,\\d+) ";
你在循环中获取它们全部:
while (m.find()) {
actual = m.group(1);
System.out.println("got last:" + actual);
}
会打印:
got last:44,66
got last:33,11
got last:11,22