仅打印匹配器中的第一个匹配项

时间:2015-06-19 03:37:19

标签: java regex

我使用以下代码在一个文档中提取用户的年龄,但他的年龄出现了几次:

Array
(
    [0] => 639152478931
    [1] => 631687515455
    [2] => 631235497891
    [3] => 0294765388389
    [4] => 52525252525
    [5] => 0012324252728
)

最后我得到了结果:

Pattern r = Pattern.compile("(\\d{2})(?=-year-old)");
Matcher matcher = r.matcher("He is a 55-year-old doctor. xxxxx. As a 55-year-old man he xxxx. When he is 55-year-old , xxxx");
if(matcher.find()) {    
                System.out.println(matcher.group(0));
                }

如何才能打印55 55 55 一次?

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以通过添加

使其变得非贪婪
Pattern r = Pattern.compile("(\\d{2})(?=-year-old)?");

应该有效,click了解详情