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