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

Don't put the minus sign between characters.

"[a-z-]"

Escape the minus sign

[a-z\\-]

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.

Tags:

Java

Regex