Reputation: 31242
I am struggling to understand a simple regex
. I googled around. somehow it is not striking me.
Here is the method:
public static void testMethod(){
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) );
System.out.println("Found value: " + m.group(3) );
}
}
Here is the output:
I was expecting group(2)
to print 3000
. but why it prints only 0
.
Upvotes: 2
Views: 71
Reputation: 5837
You need ([^0-9.]*)(\\d+)(.*)
.
The first group matching everything until last zero as you have +
in second group. You need to escape numbers from the first group.
Upvotes: 2
Reputation: 626691
Group 2 captured text only contains 0
because of the first greedy .*
. It matched up to the last digit, and let \d+
have only the last digit. See demo of your regex.
To fix it, use lazy dot matching:
(.*?)(\d+)(.*)
^
See another demo
Upvotes: 6