Regular expression to match alphanumeric, hyphen, underscore and space string

Use a simple character class wrapped with letter chars:

^[a-zA-Z]([\w -]*[a-zA-Z])?$

This matches input that starts and ends with a letter, including just a single letter.

There is a bug in your regex: You have the hyphen in the middle of your characters, which makes it a character range. ie [9-_] means "every char between 9 and _ inclusive.

If you want a literal dash in a character class, put it first or last or escape it.

Also, prefer the use of \w "word character", which is all letters and numbers and the underscore in preference to [a-zA-Z0-9_] - it's easier to type and read.


Check this working in fiddle http://refiddle.com/refiddles/56a07cec75622d3ff7c10000

This will fix the issue

 ^[a-zA-Z]+[a-zA-Z0-9-_ ]*[a-zA-Z0-9]$

As per your requirement of including space, hyphen, underscore and alphanumeric characters you can use \w shorthand character set for [a-zA-Z0-9_]. Escape the hyphen using \- as it usually used for character range inside character set.

To negate the space and hyphen at the beginning and end I have used [^\s\-].

So complete regex becomes [^\s\-][\w \-]+[^\s\-]

Here is the working demo.

Tags:

Regex