简体   繁体   中英

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

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.

Use ^[A-Z0-9]+$ as matching pattern. but matches method matches the whole string, [A-Z0-9]+ is enough.

You can try the following regular expression:

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

ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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