1
String pattern = "(.*)(\\d+)";
while(m.find()){
        System.out.println(m.group(1));
        System.out.println(m.group(2));
     } 

Input:

This order was placed for QT3000! OK?

Output :

This order was placed for QT300
0

Why in the first line of output it doesnot include the third 0 i.e QT3000? Why is the second line of output it doesnot print 3000?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
MananMehta
  • 61
  • 5
  • [Here](http://stackoverflow.com/questions/17969436/java-regex-capturing-groups), [here](http://stackoverflow.com/questions/18675870/expected-outcome-in-group-capture) and [here](http://stackoverflow.com/questions/21075643/getting-groups-of-a-pattern) amongst others... – Mena Jun 04 '15 at 12:52

3 Answers3

1

This is because of .* which is greedy and leave just one \d for the group \\d+.Make it non greedy .*? and you will get what you want.

.* will match upto the last char and then start backtracking until it finds \d.So when it encouters 0 from 3000 while coming backwards it stops right there.

.*? will stop at the first instance of \d i.e 3.So you will get 3000 in your second group.

vks
  • 67,027
  • 10
  • 91
  • 124
1

It's because .* is greedy which matches all the characters as much as possible. So .* matches all the chars upto the last and then it backtracks until it finds a digit since \d+ was given in the regex. \d+ matches one or more digits. So it won't backtrack to the next digit since the condition of matching atleast one digit was already done. Solution is, you need to make the .* as non-greedy "(.*?)(\\d+)".

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Vks and Raj have explained your question in very detail, but without examples. So I found an article on Oracle which provides a clear explanation, accompanying many examples. Hope it could help Pattern quantifier explanation

Jerry Chin
  • 657
  • 1
  • 8
  • 25