Reputation: 45
I have the following regex:
/[0-9#%@_$&!?^\/|*<>]+/i
which is not supposed to accept letters. It does accept letters when letters are not entered at the first place.
e.g.: it finds a match if I enter "123e" (but should not because there is a letter)
What is the problem in my regex?
Thanks
Upvotes: 3
Views: 70
Reputation: 26861
try by simply negating the character class that represents all letters:
/[^a-z^A-Z]+/
Upvotes: 0
Reputation: 206689
If you want the whole string to contain only the characters you specified in the regex, you'll need to anchor it:
/^[0-9#%@_$&!?^\/|*<>]+$/i
Otherwise, it looks for the specified character class anywhere in the string: as long as there is at least one of those in it, the regex would match.
Upvotes: 2
Reputation: 400932
Your regex checks if there is one or more of the list characters you specified -- and that's true for 123e
.
It doesn't check if the string contains only those.
You might want to edit your regex, so it looks like this :
/^[0-9#%@_$&!?^/|*<>]+$/i
Where I've added the two following anchors :
^
indicating "beginning of string / line"$
indicating "end of string / line"Which means the regex will check if your string starts with one of your characters, end with one of those, and contains those.
Upvotes: 2
Reputation: 490153
Use start and end anchors...
/^[\d#%@_$&!?^/|*<>]+\z/i
^
means the start of the string and \z
means the end of the string. The commonly used $
for the end of the string will allow a trailing \n
. This is not always appropriate.
Upvotes: 2
Reputation: 6279
Start the regex with ^
and end it with $
. That will make it exclusive.
^
stands for beginning of the line.
$
stands for end of the line.
Upvotes: 0