Home > Java > javaTutorial > Why Doesn\'t `String.matches()` Work as Expected with Regular Expressions?

Why Doesn\'t `String.matches()` Work as Expected with Regular Expressions?

Linda Hamilton
Release: 2024-11-26 05:18:10
Original
460 people have browsed it

Why Doesn't `String.matches()` Work as Expected with Regular Expressions?

String.matches() Doesn't Match Expected Regex

When attempting to match a specific pattern using String.matches("[a-z]"), it's surprising to find that it doesn't work as expected, even though the string contains lowercase letters.

Explanation:

The String.matches() method in Java is designed to determine if the entire input string matches the provided regular expression. In this case, the expression "[a-z]" is attempting to match a single lowercase letter. However, the code checks each string in the words array, none of which start with a lowercase letter.

Solution:

To match a pattern within a string, one should use the Pattern and Matcher classes. The Pattern class compiles the regular expression into a Matcher object, which can then be used to check for matches in the input string.

Here's a modified version of the code that uses Pattern and Matcher to find matches:

Pattern p = Pattern.compile("[a-z]+");
for(String s:words)
{
    Matcher m = p.matcher(s);
    if (m.find())
    {
        System.out.println(s);
    }
}
Copy after login

This code now correctly prints "dkoe".

The above is the detailed content of Why Doesn\'t `String.matches()` Work as Expected with Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template