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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...