Home > Java > javaTutorial > Why Doesn\'t My Regex Work in Java\'s String.matches()?

Why Doesn\'t My Regex Work in Java\'s String.matches()?

Susan Sarandon
Release: 2024-11-29 17:49:14
Original
435 people have browsed it

Why Doesn't My Regex Work in Java's String.matches()?

Regex Doesn't Work in String.matches()

Question:

A user wrote a code snippet to match strings containing only lowercase letters:

String[] words = {"{apf","hum_","dkoe","12f"};
for(String s:words)
{
    if(s.matches("[a-z]"))
    {
        System.out.println(s);
    }
}
Copy after login

However, the code does not print anything, despite expecting "dkoe" as the output.

Answer:

Contrary to its name, Java's String.matches() method matches the entire input string against a regular expression. To match only a part of the string, use Pattern and Matcher instead:

Pattern p = Pattern.compile("[a-z]+");
Matcher m = p.matcher(inputString);
if (m.find())
    // match
Copy after login

Alternatively, if you want to match the entire string, append a to the character class in the matches() method:

if(s.matches("[a-z]+"))
Copy after login

Or use a complete regex pattern:

if(s.matches("^[a-z]+$"))
Copy after login

This will match strings containing only lowercase letters, as the ^ and $ anchors ensure that the match covers the entire input string.

The above is the detailed content of Why Doesn\'t My Regex Work in Java\'s String.matches()?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template