What I need to do is to determine whether a word consists of letters except certain letters. For example I need to test whether a word consists of the letters from the English alphabet except letters: I, V and X.
Currently I have this long regex for the simple task above:
Pattern pattern = Pattern.compile("[ABCDEFGHJKLMNOPQRSTUWYZ]+");
Any of you know any shorthand way of excluding certain letters from a Java regex? Thanks.
To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).
To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.
You can use the &&
operator to create a compound character class using subtraction:
String regex = "[A-Z&&[^IVX]]+";
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