仅用于大写字母和数字的 Java 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10168694/
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
Java regex for Capital letters and numbers only
提问by p0tta
I am trying to do a simple Regex in Java and it's failing for some reason. All I want to do is, validate whether a string contains upper case letters and/or numbers. So ABC1, 111 and ABC would be valid but abC1 would not be.
我正在尝试用 Java 做一个简单的正则表达式,但由于某种原因失败了。我想要做的就是验证字符串是否包含大写字母和/或数字。因此 ABC1、111 和 ABC 将有效但 abC1 将无效。
So I tried to do this:
所以我尝试这样做:
if (!e.getId().matches("[A-Z0-9]")) {
throw new ValidationException(validationMessage);
}
I made sure that e.getId() has ABC1 but it still throws the exception. I know it's something really small and silly but i'm unable to figure it out.
我确保 e.getId() 有 ABC1 但它仍然抛出异常。我知道这是一件非常小而愚蠢的事情,但我无法弄清楚。
回答by Prince John Wesley
Use ^[A-Z0-9]+$
as matching pattern. but matches
method matches the whole string, [A-Z0-9]+
is enough.
使用^[A-Z0-9]+$
的匹配模式。但是matches
方法匹配整个字符串,[A-Z0-9]+
就足够了。
回答by Paul Vargas
You can try the following regular expression:
您可以尝试以下正则表达式:
[\p{Digit}\p{Lu}]+
i.e.:
IE:
if (!e.getId().matches("[\p{Digit}\p{Lu}]+")) {
throw new ValidationException(validationMessage);
}