I was looking at a code at TutorialsPoint and something has been bothering me since then... take a look at this code :
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);
while(m.find( )) {
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
System.out.println("Found value: " + m.group(3));
}
}
}
this code successfully prints :
Found value: This was placed for QT300
Found value: 0
Found value: ! OK?
but according to the regex "(.*)(\d+)(.*)"
, why doesn't it return other possible outcomes such as :
Found value: This was placed for QT30
Found value: 00
Found value: ! OK?
or
Found value: This was placed for QT
Found value: 3000
Found value: ! OK?
and if this code isn't suited to do so, then how can I write one that can find all possible matches ?
See Question&Answers more detail:os