+ 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"); } } }
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
+ 2
zemiak thamks for sharing the 3 modes . Thats the better answer.
+ 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+)(.*)";