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

Tags: regex java
By : daveb
Pattern pattern = Pattern.compile("^[a-z]+$");
String string = "abc-def";
assertTrue( pattern.matcher(string).matches() ); // obviously fails

Is it possible to have the character class match a "-" ?

By : daveb


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:




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:


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


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

By : codaddict

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.

By : John M

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

This video can help you solving your question :)
By: admin