1

I have this regex:

/^[A-z0-9\._-]{3,24}+$/i

This is supposed to only match a string between 3 and 24 characters long, and only with the characters a-z, A-Z, 0-9, and then also the . _ and - characters.

The problem is this is also matching strings like "^_^". Someone just created a username with exactly that, so this is definitely a problem! Can anyone spot the problem with my regex?

1
  • According to regexr, your pattern has a syntax error; strange why PCRE doesn't seem to care about it. Commented Jun 11, 2014 at 17:59

2 Answers 2

3

Use this regex:

/^[\w.-]{3,24}$/

A-z is not same as [A-Za-z] as it also includes other characters such as ^ (thanks Jack)

Also remove extra quantifier + after {3,24} which means one or more instances of whole string.

PS: I have also shortened your regex to use \w instead of [A-Za-z0-9_]

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

5 Comments

Awesome. Nice and simple! Thanks. I have to wait a couple more minutes before I can accept the answer.
Actually, the + has no ill effects (even though it shouldn't be there). What you have "masked" as shortening the regex is actually the fix, because the A-z range includes ^ :)
@Jack: Thanks I overlooked that part, added in my answer.
wow, i thought A-z was a-z and A-Z. are all the special characters included in A-z?
A-z includes all characters in the range from 65 to 122 in ASCII table
2

You do not need the + as you are specifying a range of lengths with the {3,24}

/^[A-z0-9\._-]{3,24}$/i

As was pointed out in the comments below, A-z matches the ^ character, as well. In this case A-Za-z would be better; however, the answer above with \w.- is the most elegant by far.

2 Comments

This still matches "^_^".
You are correct, I should not have used A-z in this case, rather A-Za-z. But, frankly, I consider @anubhava's answer more elegant anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.