Regex doesn't work in String.matches()

前端 未结 9 1053
余生分开走
余生分开走 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:50

    [a-z] matches a single char between a and z. So, if your string was just "d", for example, then it would have matched and been printed out.

    You need to change your regex to [a-z]+ to match one or more chars.

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

    Used

    String[] words = {"{apf","hum_","dkoe","12f"};
        for(String s:words)
        {
            if(s.matches("[a-z]+"))
            {
                System.out.println(s);
            }
        }
    
    0 讨论(0)
  • 2020-11-22 13:52

    you must put at least a capture () in the pattern to match, and correct pattern like this:

    String[] words = {"{apf","hum_","dkoe","12f"};
    for(String s:words)
    {
        if(s.matches("(^[a-z]+$)"))
        {
            System.out.println(s);
        }
    }
    
    0 讨论(0)
提交回复
热议问题