In a java regex, how can I get a character class e.g. [a-z] to match a - minus sign?

后端 未结 5 766
庸人自扰
庸人自扰 2020-12-06 10:19
Pattern pattern = Pattern.compile(\"^[a-z]+$\");
String string = \"abc-def\";
assertTrue( pattern.matcher(string).matches() ); // obviously fails

I

相关标签:
5条回答
  • 2020-12-06 10:28

    Inside a character class [...] a - is treated specially(as a range operator) if it's surrounded by characters on both sides. That means if you include the - at the beginning or at the end of the character class it will be treated literally(non-special).

    So you can use the regex:

    ^[a-z-]+$
    

    or

    ^[-a-z]+$
    

    Since the - that we added is being treated literally there is no need to escape it. Although it's not an error if you do it.

    Another (less recommended) way is to not include the - in the character class:

    ^(?:[a-z]|-)+$
    

    Note that the parenthesis are not optional in this case as | has a very low precedence, so with the parenthesis:

    ^[a-z]|-+$
    

    Will match a lowercase alphabet at the beginning of the string and one or more - at the end.

    0 讨论(0)
  • 2020-12-06 10:33

    Escape the minus sign

    [a-z\\-]
    
    0 讨论(0)
  • 2020-12-06 10:36

    Don't put the minus sign between characters.

    "[a-z-]"
    
    0 讨论(0)
  • 2020-12-06 10:40

    This works for me

       Pattern p = Pattern.compile("^[a-z\\-]+$");
       String line = "abc-def";
       Matcher matcher = p.matcher(line);
       System.out.println(matcher.matches());  // true
    
    0 讨论(0)
  • 2020-12-06 10:48

    I'd rephrase the "don't put it between characters" a little more concretely.

    Make the dash the first or last character in the character class. For example "[-a-z1-9]" matches lower-case characters, digits or dash.

    0 讨论(0)
提交回复
热议问题