p0tta
p0tta

Reputation: 1651

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.

Upvotes: 3

Views: 26085

Answers (2)

Paul Vargas
Paul Vargas

Reputation: 42040

You can try the following regular expression:

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

i.e.:

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

Upvotes: 6

Prince John Wesley
Prince John Wesley

Reputation: 63698

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

Upvotes: 14

Related Questions