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

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -