这两个正则表达式之间有什么区别吗?

时间:2016-11-06 07:56:41

标签: regex

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

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

在Java中。它们看起来和我完全一样。

1 个答案:

答案 0 :(得分:2)

两者之间存在细微差别。以下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.");
        }
    }
}

提供输出:

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

因此,在字符串abc的情况下,第一个正则表达式创建一个具有空内容的捕获组,而在第二个正则表达式中,该组是空的,因此不匹配。虽然我不熟悉Java,但我猜你必须对它们有所不同。

旁注:

Java不支持条件匹配(不同于PCRE,.net,Boost等)和条件替换(与Boost不同),这会产生巨大的差异。哦,德尔福有issues with optional named capturing groups