miguello
miguello

Reputation: 584

Regex match between n and m numbers but as much as possible

I have a set of strings that have some letters, occasional one number, and then somewhere 2 or 3 numbers. I need to match those 2 or 3 numbers. I have this:

\w*(\d{2,3})\w*

but then for strings like

AAA1AAA12A
AAA2AA123A

it matches '12' and '23' respectively, i.e. it fails to pick the three digits in the second case. How do I get those 3 digits?

Upvotes: 0

Views: 271

Answers (2)

WJS
WJS

Reputation: 40062

Here is how you would do it in Java.

  • the regex simply matches on a group of 2 or 3 digits.
  • the while loop uses find() to continue finding matches and the printing the captured match. The 1 and the 1223 are ignored.
String s=   "AAA1AAA12Aksk2ksksk21sksksk123ksk1223sk";
String regex = "\\D(\\d{2,3})\\D";
Matcher  m = Pattern.compile(regex).matcher(s);
while (m.find()) {
    System.out.println(m.group(1));
}

prints

12
21
123

Upvotes: 3

miguello
miguello

Reputation: 584

Looks like the correct answer would be:

    \w*?(\d{2,3})\w*

Basically, making preceding expression lazy does the job

Upvotes: 2

Related Questions