2015-06-19 91 views
0

我用下面的代碼來提取用戶的年齡在一份文件中,但他的年齡出現了幾次:打印僅在匹配中第一次出現

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 

如何才能打印55一次?

在此先感謝。

+6

您的代碼,因爲它是打印'55'只有一次。那不是你想要的? – Codebender

+0

@abishek,他只想要第一個例子。 – Mox

+0

向我們展示您使用的整個循環。 – Basilevs

回答

0

您可以通過添加使其非貪婪?

Pattern r = Pattern.compile("(\\d{2})(?=-year-old)?"); 

應該工作,click查看詳細

相關問題