Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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 "-" ?

like image 916
daveb Avatar asked Sep 30 '08 17:09

daveb


People also ask

How do I match a regular character in regex?

A regular character in the RegEx Java syntax matches that character in the text. If you'll create a Pattern with Pattern.compile ("a") it will only match only the String "a".

What is a character class in regex?

This regex means characters “l”, “m”, “n”, “o”, “p” would match in a string. Subtraction of ranges also works in character classes. This regex means vowels are subtracted from the range “a-z”. Regex patterns discussed so far require that each position in the input string match a specific character class.

What is a Java regex?

Then, at the end of the article, we provide a Java RegEx cheat sheet PDF that gives you all RegEx shortcuts on one page. But first, let's start with the basics. What Is a Java Regular Expression? A Java regular expression, or Java regex, is a sequence of characters that specifies a pattern which can be searched for in a text.

How many characters does the expression “*” match in Java?

Similarly the expression “.*” matches n number of characters. Following Java program reads 5 strings from the user and accepts those which starts with b, ends with a with any number of characters in between them.


1 Answers

Don't put the minus sign between characters.

"[a-z-]"
like image 144
Tomalak Avatar answered Oct 22 '22 21:10

Tomalak