为什么Java和Perl中的正则表达式有不同的表现? [英] Why do regular expressions in Java and Perl act differently?
问题描述
我的理解是Java的正则表达式的实现是基于Perl的。但是,在下面的示例中,如果我使用相同的字符串执行相同的正则表达式,Java和Perl会返回不同的结果。
My understanding is that Java's implementation of regular expressions is based on Perl's. However, in the following example, if I execute the same regex with the same string, Java and Perl return different results.
这是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不认为它是匹配的。造成这种差异的原因是什么?
To me, the Perl result makes sense. It looks for a match for a single word character. I don't understand why Java doesn't consider it a match. What's the reason for the difference?
推荐答案
Java 匹配
方法是测试正则表达式是否匹配整个 String
。要测试是否可以在字符串中的任何位置找到正则表达式,请创建 Matcher
并使用其 find
方法。
The Java matches
method is testing whether the regex matches the entire String
. To test whether a regex can be found anywhere in a string, create a Matcher
and use its find
method.
这篇关于为什么Java和Perl中的正则表达式有不同的表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!