The ?
after greedy operators such as +
or *
will make the operator non greedy. Without the ?
, that regex will keep matching all the characters it finds, including the :
.
As it is, the regex will match any string which happens before the semi colon (:
). In this case, the semicolon is not a special character. What ever comes before the semicolon, will be thrown into a group, which can be accessed later through a Matcher
object.
This code snippet will hopefully make things more clear:
String str = "Hello: This is a Test:";
Pattern p1 = Pattern.compile("(.*?):");
Pattern p2 = Pattern.compile("(.*):");
Matcher m1 = p1.matcher(str);
if (m1.find())
{
System.out.println(m1.group(1));
}
Matcher m2 = p2.matcher(str);
if (m2.find())
{
System.out.println(m2.group(1));
}
Yields:
Hello
Hello: This is a Test