Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

regex - Why do regular expressions in Java and Perl act differently?

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.

Here's the Java example:

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" );
    }
}

This returns: Doesn't match

Here's the Perl example:

my $sentence = 'This is a test of regular expressions.';
print ( $sentence =~ /w/ ? "Matches" : "Doesn't match" ) . "
";

This returns: Matches

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...