简体   繁体   English

仅适用于大写字母和数字的Java正则表达式

[英]Java regex for Capital letters and numbers only

I am trying to do a simple Regex in Java and it's failing for some reason. 我试图在Java中做一个简单的正则表达式,但由于某种原因它失败了。 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. 因此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. 我确保e.getId()有ABC1,但它仍然抛出异常。 I know it's something really small and silly but i'm unable to figure it out. 我知道这是一个非常小而愚蠢的东西,但我无法弄明白。

Use ^[A-Z0-9]+$ as matching pattern. 使用^[A-Z0-9]+$作为匹配模式。 but matches method matches the whole string, [A-Z0-9]+ is enough. matches方法匹配整个字符串, [A-Z0-9]+就足够了。

You can try the following regular expression: 您可以尝试以下正则表达式:

[\p{Digit}\p{Lu}]+

ie: 即:

if (!e.getId().matches("[\\p{Digit}\\p{Lu}]+")) {
    throw new ValidationException(validationMessage);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM