Can someone tell me what the syntax for a regex would be that would only allow the following characters:
a-z
A-Z
0-9
dash
underscore
Additionally the string cannot contain more than 5 numbers.
Thank you in advance for the help!
Can someone tell me what the syntax for a regex would be that would only allow the following characters:
a-z
A-Z
0-9
dash
underscore
Additionally the string cannot contain more than 5 numbers.
Thank you in advance for the help!
The regex you need is
^[a-zA-Z0-9_-]{0,5}$
It matches any combination of the characters up to five characters.
several possibilities:
~\A(?:[a-z_-]*[0-9]){0,5}[a-z_-]*\z(?<=.)~i
or
~\A(?!(?:.*[0-9]){6})[\w-]+\z~
The two patterns assumes that the empty string is not allowed.
First pattern:
~ # pattern delimiter
\A # anchor for the start of the string
(?:[a-z_-]*[0-9]){0,5} # repeat this group between 0 or 5 times (so 5 digits max)
[a-z_-]* # zero or more allowed characters
\z # end of the string
(?<=.) # lookbehind that checks there is at least one character
~
i # make the pattern case insensitive
second pattern:
~
\A
(?! # negative lookahead that checks there is not
(?:.*[0-9]){6} # 6 digits in the string
)
[\w-]+
\z
~