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-Zd-_@&$%#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
Advertisement
Answer
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 fiftyp{L}
– any Unicode letterp{N}
– any Unicode digit_@,.&$%#-
– any of these charss
– any whitespace
$
– end of string.