Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex include all letters of the alphabet except certain letters

Tags:

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.

like image 977
user3367701 Avatar asked Sep 01 '14 15:09

user3367701


People also ask

How do you match a character except one regex?

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).

How do you regex only letters?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.


1 Answers

You can use the && operator to create a compound character class using subtraction:

String regex = "[A-Z&&[^IVX]]+";
like image 138
Keppil Avatar answered Sep 27 '22 17:09

Keppil