3

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

2
  • If it isn't supposed to match any letters, why did you add the /i flag? Just wondering :) Commented Jul 21, 2011 at 5:29
  • Thank you all for your help, it did work with ^ and $ (/^[0-9#%@_$&!?^/|*<>]+$/i) Commented Jul 21, 2011 at 5:30

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Will $ really allow \n without the /m flag?
2

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.

3 Comments

what about ., ` and ~ for example?
what about them? the OP says his RE was not supposed to match characters, not that that was the only thing he didn't want to match.
as I understand from the question, he wants the regex to match any character that is not a letter
0

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.

Comments

0

try by simply negating the character class that represents all letters:

/[^a-z^A-Z]+/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.