[ACCEPTED]-Need a regex that will check if the string only consist letters a-z and numbers and underscore(_) and hyphen(-)-regex

Accepted answer
Score: 18

You have to put your regex /^a-zA-Z0-9_-$/ in a character 12 class /[...]/.
It means you can match any character 11 in the character class. You should also 10 specify a quantifier, because /^[a-zA-Z0-9_-]$/ will match 9 only one character.

/^[a-zA-Z0-9_-]+$/ with the 8 + sign you match it one or more time
/^[a-zA-Z0-9_-]{1,}$/ the 7 same as above
/^[a-zA-Z0-9_-]{10,20}$/ between 10 and 20 character 6 long.
/^[a-zA-Z0-9_-]{15}$/ it has to be exactly 15 characters long. You 5 can use it to check the string length.

You 4 can also use the following keyword to make 3 your regex easy to read:
/^[\w-]+$/ which matches 2 a word character (including underscore, letters 1 and digits) or a dash, one or more time.

Score: 7

I would use this one:


As to why I'm not using 8 \w, the following quote, taken from PHP PCRE Pattern Reference, should 7 explain why you shouldn't be using \w in this situation:

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

That behavior is not desirable 6 in this case, so unless you want to worry 5 about locale, use straight character classes 4 instead of the \w shorthand.

If you want to 3 specify a minimum length (for example 3):


If 2 you want to specify both a minimum and maximum 1 length (for example 2 and 5):

Score: 4

Shortest one:



Score: 2

The regex should be: '^[\w\d-]+$'


Score: 1

The answers so far correctly explain the 9 character class /^[A-Za-z0-9_-]+$/

You can check the length. + means 8 "one or more of the preceding", * means 7 zero or more of the preceding" and {2,4} means 6 "between 2 and 4 of the preceding".

You 5 can't specify the length has to be a prime, though. Specifying 4 that the length has to be even is possible 3 but non-trivial: /^(xx){1,3}$/ matches xx, xxxx or 2 xxxxxx. The count here refers to the number of pairs, not 1 the number of x'es

More Related questions