user697911
user697911

Reputation: 10571

Any difference between these two regular expression?

abc([^\r\n]*) // 0 or more

abc([^\r\n]+)? // 1 or more, but it's optional  

In Java. They look exactly the same to me.

Upvotes: 1

Views: 65

Answers (1)

Sebastian Proske
Sebastian Proske

Reputation: 8413

There is a small difference between the two. The following code

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Example
{
    public static void main (String[] args)
    {
        String text = "abc";
        Pattern p1 = Pattern.compile("abc([^\\r\\n]*)");
        Matcher m1 = p1.matcher(text);
        if (m1.find()) {
            System.out.println("MatchCount: " + m1.groupCount());
            System.out.println("Group 1: " + m1.group(1));
        } else {
            System.out.println("No match.");
        }
        Pattern p2 = Pattern.compile("abc([^\\r\\n]+)?");
        Matcher m2 = p2.matcher(text);
        if (m2.find()) {
            System.out.println("MatchCount: " + m2.groupCount());
            System.out.println("Group 1: " + m2.group(1));
        } else {
            System.out.println("No match.");
        }
    }
}

Gives output:

MatchCount: 1
Group 1: 
MatchCount: 1
Group 1: null

So in case of string abc the first regex creates a capturing group with empty content, while in the second the group is empty and thus not matched. Though I'm not that familiar with Java, I'd guess you will have to treat them a bit different.

Sidenote:

Java doesn't support conditional matching (unlike PCRE, .net, Boost and some more) and conditional replacing (unlike Boost) where this would make a huge difference. Oh and Delphi has issues with optional named capturing groups.

Upvotes: 2

Related Questions