Reputation: 177
How shall we write a regular expression to validate a string that should have a length of a minimum of 1 character and a maximum of 50 characters, have both upper case and lower case, alphanumeric, include space, and have mostly used special characters like @,._-&$#? The first character should be either alphabet or number then the rest can be as mentioned above.
*If it is only one character then it should be an alphanumeric one
I have tried a regex with my limited knowledge which looks like
^[a-zA-z]*[a-zA-Z\d\-_@&$%#\s]{1,50}$
But I am not able to match the string if there is only one character given, can anyone guide me to fix this
Upvotes: 2
Views: 2460
Reputation: 626799
You can use
/^(?=[\p{L}0-9])[\p{L}\p{N}_@,.&$%#\s-]{1,50}$/u
See the regex demo
Details
^
- start of string(?=[\p{L}0-9])
- the first char must be a Unicode letter (\p{L}
) or an ASCII digit[\p{L}\p{N}_@,.&$%#\s-]{1,50}
- one to fifty
\p{L}
- any Unicode letter\p{N}
- any Unicode digit_@,.&$%#-
- any of these chars\s
- any whitespace$
- end of string.Upvotes: 2