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
Susan SarandonOriginal
2024-11-29 17:49:14327browse

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

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

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

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

Or use a complete regex pattern:

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

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:
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