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


i'm trying match string contains alphanumeric, hyphen, underscore , space.

hyphen, underscore, space , numbers optional, first , last characters must letters.

for example, these should match:

abc abc def abc123 ab_cd ab-cd 

i tried this:

^[a-za-z0-9-_ ]+$ 

but matches space, underscore or hyphen @ start/end, should allow in between.

use simple character class wrapped letter chars:

^[a-za-z]([\w -]*[a-za-z])?$ 

this matches input starts , ends letter, including single letter.

there bug in regex: have hyphen in middle of characters, makes character range. ie [9-_] means "every char between 9 , _ inclusive.

if want literal dash in character class, put first or last or escape it.

also, prefer use of \w "word character", letters , numbers , underscore in preference [a-za-z0-9_] - it's easier type , read.


Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -