-1

I use the following code to extract the age of a user in one document, but his age appears several times:

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));
                }

Finally I get the result:

55
55
55

How can I just print 55 once?

Thanks in advance.

Steven Luo
  • 2,350
  • 3
  • 18
  • 35

1 Answers1

-1

You can make it non-greedy by adding ?

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

should work, click for detail

Community
  • 1
  • 1
TheCodingFrog
  • 3,406
  • 3
  • 21
  • 27