Java 正则表达式包括除某些字母外的所有字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25608925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:20:00  来源:igfitidea点击:

Java Regex include all letters of the alphabet except certain letters

javaregex

提问by user3367701

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.

我需要做的是确定一个单词是否由某些字母以外的字母组成。例如,我需要测试一个单词是否由英文字母表中的字母组成,除了字母:I、V 和 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.

你们中有人知道从 Java 正则表达式中排除某些字母的速记方法吗?谢谢。

回答by Keppil

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

您可以使用&&运算符通过减法创建复合字符类:

String regex = "[A-Z&&[^IVX]]+";

回答by p.s.w.g

You could simply specify character ranges inside your character class:

您可以简单地在字符类中指定字符范围:

[A-HJ-UWYZ]+

回答by Avinash Raj

Just use a negative lookahead in your pattern.

只需在您的模式中使用负前瞻。

Pattern pattern = Pattern.compile("^(?:(?![IVX])[A-Z])+$");

DEMO

演示

回答by Viktor13710

'&&' didn't work for me,

“&&”对我不起作用,

used: (?:(?![IVX])[A-Z])

用过的: (?:(?![IVX])[A-Z])

回答by bcsb1001

Use [A-Z&&[^IVX]]+to exclude certain characters from the A-Zrange - see Pattern

用于[A-Z&&[^IVX]]+A-Z范围中排除某些字符- 请参阅模式