3

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.

4

2 に答える 2

12

^[A-Z0-9]+$マッチングパターンとして使用します。ただし、matchesメソッドは文字列全体に一致する[A-Z0-9]+だけで十分です。

于 2012-04-16T04:30:02.383 に答える
6

次の正規表現を試すことができます。

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

すなわち:

if (!e.getId().matches("[\\p{Digit}\\p{Lu}]+")) {
    throw new ValidationException(validationMessage);
}
于 2012-04-16T04:30:40.367 に答える