Reputation: 11
I am trying to create a regular expression that does not allow any special characters, but also requires at least one letter (alphabet) to pass. The alphabet can be capital or lowercase.
Example required pass and fail cases
I would also like to allow -, and _ characters.
This is what I have created so far: ^(?=.*[A-Z]).{3,25}$
The above RegEx checks to make sure that an alphabet exists within the expression, but I would also like to disallow special characters.
Can someone explain how I can add the extra check within the same regular expression?
Upvotes: 1
Views: 1568
Reputation: 163207
If you dont' want to allow -
or spaces at the start or at the end, you could use 2 lookahead assertions, 1 for the number of characters and the other one to assert a char A-Z.
^(?=[^A-Z]*[A-Z])(?=.{3,25}$)\w+(?:[\h-]\w+)*$
Explanation
^
Start of string(?=[^A-Z]*[A-Z])
Assert an uppercase char A-Z(?=.{3,25}$)
Assert 3 - 25 chars\w+
Match 1+ word chars(?:[\h-]\w+)*
Repeat 0+ times matching either a horizontal whitespace char or -
$
End of stringUpvotes: 1
Reputation: 5224
Change the .
to be your allowed character list. Something like:
^(?=.*?[A-Z])[\w\h-]{3,25}$
https://regex101.com/r/j4wuUP/2/
[\w\h-]
(\w
) allows for a-zA-Z0-9_
, (\h
) horizontal whitespace, and -
s. The -
must be first, last, or escaped; otherwise it will create a range of ascii characters. In non-PCRE flavors escaping is not possible so it must be first or last.
Upvotes: 0