5

I've got a simple regex, which should match only letters and numbers in last 4 chars of string:

([a-zA-Z0-9]{4}$)

It works perfectly in online tester, but doesn't match if i use it with hibernate validation annotation on field:

@NotNull
@Length(min = 4, max = 25)
@Pattern(regexp = "([a-zA-Z0-9]{4}$)")
private String test;

For example, it returns false for 1234.5678-abC2 string

Could you help me?

4
  • Your regex doesn't match the . character. Add \\. within the [ ]. Commented Sep 10, 2015 at 15:00
  • My regex should check that last 4 chars of input string don't contain special chars. So, . not supposed to be matched. I'm not sure that i understand you correctly. Coluld you please give an example? Commented Sep 10, 2015 at 15:10
  • 2
    You are assuming that the @Pattern annotation will return true if a substring regex match passes. If it isn't working then your assumption may not be true. Try adding .* in the beginning of your pattern string Commented Sep 10, 2015 at 15:22
  • please mark either of the answers below as the accepted answer for future reference. Commented Nov 20, 2019 at 11:18

2 Answers 2

5

For future visitors, I would add the response of @hofan41 provided in the main OP comment.

You are assuming that the @Pattern annotation will return true if a substring regex match passes. If it isn't working then your assumption may not be true. Try adding .* in the beginning of your pattern string.

In such a manner, the bean property validation annotations will look as follows:

@NotNull
@Length(min = 4, max = 25)
@Pattern(regexp = ".*([a-zA-Z0-9]{4}$)")
private String test;
Sign up to request clarification or add additional context in comments.

Comments

5

The pattern matches against the entire region as can be seen in the following PatternValidator code:

public boolean isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext) {
    if ( value == null ) {
        return true;
    }
    Matcher m = pattern.matcher( value );
    return m.matches();
}

...And from the documentation for Matcher.matches:

Attempts to match the entire region against the pattern.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.