Regex doesn't work in String.matches()

前端 未结 9 1044
余生分开走
余生分开走 2020-11-22 13:21

I have this small piece of code

String[] words = {\"{apf\",\"hum_\",\"dkoe\",\"12f\"};
for(String s:words)
{
    if(s.matches(\"[a-z]\"))
    {
        Syste         


        
相关标签:
9条回答
  • 2020-11-22 13:36

    Welcome to Java's misnamed .matches() method... It tries and matches ALL the input. Unfortunately, other languages have followed suit :(

    If you want to see if the regex matches an input text, use a Pattern, a Matcher and the .find() method of the matcher:

    Pattern p = Pattern.compile("[a-z]");
    Matcher m = p.matcher(inputstring);
    if (m.find())
        // match
    

    If what you want is indeed to see if an input only has lowercase letters, you can use .matches(), but you need to match one or more characters: append a + to your character class, as in [a-z]+. Or use ^[a-z]+$ and .find().

    0 讨论(0)
  • 2020-11-22 13:36

    java's implementation of regexes try to match the whole string

    that's different from perl regexes, which try to find a matching part

    if you want to find a string with nothing but lower case characters, use the pattern [a-z]+

    if you want to find a string containing at least one lower case character, use the pattern .*[a-z].*

    0 讨论(0)
  • 2020-11-22 13:36

    I have faced the same problem once:

    Pattern ptr = Pattern.compile("^[a-zA-Z][\\']?[a-zA-Z\\s]+$");
    

    The above failed!

    Pattern ptr = Pattern.compile("(^[a-zA-Z][\\']?[a-zA-Z\\s]+$)");
    

    The above worked with pattern within ( and ).

    0 讨论(0)
  • 2020-11-22 13:44

    String.matches returns whether the whole string matches the regex, not just any substring.

    0 讨论(0)
  • 2020-11-22 13:44

    Your regular expression [a-z] doesn't match dkoe since it only matches Strings of lenght 1. Use something like [a-z]+.

    0 讨论(0)
  • 2020-11-22 13:44

    You can make your pattern case insensitive by doing:

    Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
    
    0 讨论(0)
提交回复
热议问题