I want an alphanumeric (not a word) string between 3 and 50 characters long. It can have no more that 3 whitespaces in it. The best I've come up with is:
^[a-zA-Z0-9]{3,50}[\s]{0,3}$
but this doesn't work.
Can someone please point me in the right direction?
CodePudding user response:
As Cary Swoveland has suggested in the comments, you may use a negative Lookahead to ensure that the string doesn't have more than 3 whitespace characters. The full pattern would be something like this:
^(?!(?:.*\h){4})[A-Za-z0-9\h]{3,50}$
Demo.
Note that I used \h
instead of \s
here in order to only match horizontal whitespace characters.
If you need to prevent whitespace characters from appearing at the beginning/end of the string, you could adjust the Lookahead and add a negative Lookbehind at the end:
^(?!\h|(?:.*\h){4})[A-Za-z0-9\h]{3,50}(?<!\h)$
Demo.