I have a some issue with pattern for java bean validation. I have a pattern for my variable inside java class
@Pattern(regexp = ".*[A-Z]+[[A-Z]\\p{Space}]+[A-Z\\p{Punct}]+([0-9]{1,10})?", message = "Error")*
private String name;
And actually it's working, but now I have to add a range {0,32} to uppercase words. When I added [A-Z]{0,32} it breaks down
The name should fit values below
How to change/refactor that pattern to possible to add range for uppercase letter and 2, 5, 12 would working?
The solution is "(?=.*[A-Z])[\p{Punct}A-Z0-9 ]{1,32}"
You may use
@Pattern(regexp = "(?=.*[A-Z])[\\p{Punct}A-Z0-9 ]{1,32}", message = "Error")
See the regex demo
Since the pattern is anchored by default (it is used with .matches()
method), no ^
and $
are necessary around the pattern.
It matches:
(?=.*[A-Z])
- after any 0+ chars other than linebreak chars there must be at least 1 uppercase ASCII letter[\\p{Punct}A-Z0-9 ]{1,32}
- match 1 to 32 uppercase ASCII letters, digits, space or chars from the Punct POSIX character class (it includes punctuation and symbols).