问题
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.
回答1:
You can use the &&
operator to create a compound character class using subtraction:
String regex = "[A-Z&&[^IVX]]+";
回答2:
You could simply specify character ranges inside your character class:
[A-HJ-UWYZ]+
回答3:
Just use a negative lookahead in your pattern.
Pattern pattern = Pattern.compile("^(?:(?![IVX])[A-Z])+$");
DEMO
回答4:
Use [A-Z&&[^IVX]]+
to exclude certain characters from the A-Z
range - see Pattern
来源:https://stackoverflow.com/questions/25608925/java-regex-include-all-letters-of-the-alphabet-except-certain-letters