Why does the second group only print one digit and not all of them? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why does the second group only print one digit and not all of them?

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String args[] ) { // String to be scanned to find the pattern. String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); } else { System.out.println("NO MATCH"); } } }

4th Jul 2020, 11:15 PM
Ibrahim Adeosun
Ibrahim Adeosun - avatar
3 Answers
+ 4
The second group prints only the last digit because the previous digits are included in the first group. You see better what happens if you replace 0000 with 1234. To get all digits in the second group, a better regular expressiin would be (\\D*)(\\d+)(.*) see example code https://code.sololearn.com/cfa19sKRh9pA/?ref=app
5th Jul 2020, 12:27 AM
ifl
ifl - avatar
+ 2
zemiak thamks for sharing the 3 modes . Thats the better answer.
5th Jul 2020, 7:17 AM
ifl
ifl - avatar
+ 1
there are three modes (quantifiers): Greedy (get max, respect others) default ? Reluctant (get one) + Possessive (skip max, no respect) try second String pattern = "(.*?)(\\d+)(.*)";
5th Jul 2020, 12:59 AM
zemiak