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 "-" ?
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".
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.
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.
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.
Don't put the minus sign between characters.
"[a-z-]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With