Pattern pattern = Pattern.compile(\"^[a-z]+$\");
String string = \"abc-def\";
assertTrue( pattern.matcher(string).matches() ); // obviously fails
I
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.
Escape the minus sign
[a-z\\-]
Don't put the minus sign between characters.
"[a-z-]"
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
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.