Java – @Pattern , JSR303 bean validation : regex check max 5 words and not blank

bean-validationjavaregexspring-mvc

I use JSR303 bean validation annotations in my spring-mvc managed bean to validate text input.
I need to check

  • if a string contains max 5 words (Here a word is an alphabetic or alphanumeric string)
    and this string can't be blank (one space)

I try with this : ( just to match 5 words)

@Pattern(message="max 5 words please" , regexp="^[a-zA-Z+#\-.0-9]{1,5}(\s[a-zA-Z+#\-.0-9]{1,5}){0,4}$")
String keywords;

but my Eclipse IDE says :
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )

Best Answer

You could try this shorter version if you want.

regexp="^(\\b[a-zA-Z\\d+#.-]+\\b(?:\\s+|$)){0,5}$")

Should work.

Btw in your regex you say :

Match one to five chars (word of max 5 chars?), (followed by space, followed by zero to four chars. ) zero or four times. Is this what you want? :)