I am trying to make a regular expression, that allow to create string with the small and big letters + numbers – a-zA-z0-9 and also with the chars: .-_
How do I make such a regex?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The following regex should be what you are looking for (explanation below):
The following character class should match only the characters that you want to allow:
You could shorten this to the following since
\wis equivalent to[a-zA-z0-9_]:Note that to include a literal
-in your character class, it needs to be first character because otherwise it will be interpreted as a range (for example[a-d]is equivalent to[abcd]). The other option is to escape it with a backslash.Normally
.means any character except newlines, and you would need to escape it to match a literal period, but this isn’t necessary inside of character classes.The
\Aand\zare anchors to the beginning and end of the string, otherwise you would match strings that contain any of the allowed characters, instead of strings that contain only the allowed characters.The
*means zero or more characters, if you want it to require one or more characters change the*to a+.