1
abc([^\r\n]*) // 0 or more
abc([^\r\n]+)? // 1 or more, but it's optional
在Java中。他们看起来和我完全一样。这两个正则表达式有什么区别?
abc([^\r\n]*) // 0 or more
abc([^\r\n]+)? // 1 or more, but it's optional
在Java中。他们看起来和我完全一样。这两个正则表达式有什么区别?
两者之间有一个小的差异。下面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,升压和多一些)和有条件的更换(不像升压),其中,这将产生巨大的变化。哦,德尔福有issues with optional named capturing groups。
它们对我来说也是一样。 –
如果使用'abc',第一个会将一个空字符串存储到第一个捕获组中,第二个不会存储这个组,但是我对Java不熟悉,无法知道当您尝试访问组时会发生什么1.请注意,在支持条件匹配(PCRE,Boost,.net等)或替换(Boost)的其他正则表达式中,这可能会产生巨大差异。哦,德尔福在访问不匹配的命名捕获群组时遇到问题。 –
哇。我只是测试它,我想我发布了错误的答案。 https://regex101.com/r/H6nkxD/1表明不同的解析器对于组“'(...)”的行为确实有区别吗?''' – Art