【发布时间】:2009-04-24 02:05:31
【问题描述】:
我的理解是Java对正则表达式的实现是基于Perl的。但是,在下面的示例中,如果我使用相同的字符串执行相同的正则表达式,Java 和 Perl 会返回不同的结果。
这是 Java 示例:
public class RegexTest {
public static void main( String args[] ) {
String sentence = "This is a test of regular expressions.";
System.out.println( sentence.matches( "\\w" ) ? "Matches" : "Doesn't match" );
}
}
返回:不匹配
这是 Perl 示例:
my $sentence = 'This is a test of regular expressions.';
print ( $sentence =~ /\w/ ? "Matches" : "Doesn't match" ) . "\n";
这会返回:匹配
对我来说,Perl 的结果是有意义的。它查找单个单词字符的匹配项。我不明白为什么 Java 不认为它是匹配的。造成差异的原因是什么?
【问题讨论】: