Home > database >  Regex match between n and m numbers but as much as possible
Regex match between n and m numbers but as much as possible

Time:07-13

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?

CodePudding user response:

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

CodePudding user response:

Looks like the correct answer would be:

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

Basically, making preceding expression lazy does the job

  • Related