• Howdy! Welcome to our community of more than 130.000 members devoted to web hosting. This is a great place to get special offers from web hosts and post your own requests or ads. To start posting sign up here. Cheers! /Peo, FreeWebSpace.net
managed wordpress hosting

RegEx help

Agum

New Member
I need a RegEx pattern that checks for usernames.
The username must consist of only alphanumeric characters or hyphen (-) or underscore (_).
The thing is, hyphen or underscore must have an alphanumeric character before and after it.

Test cases:
Spiderman = ok
Spider-man = ok
Spider_man = ok
Spider--man = err
Spider__man = err
-Spiderman = err
Spiderman_ = err
Spider-man-2 = ok
1_Spider-man = ok

Can anyone help me with a quick little pattern?
Thanks.

(edit)
me and my friend came up with two different ways to do this:
^[a-zA-Z0-9]+([-_][a-zA-Z0-9]+)*$
matches the "good" stuff (return true on OK, return false on ERR)
^[-_]|[^a-zA-Z0-9-_]|(--)|(-_)|(_-)|(__)|[-_]$
matches the "bad" stuff (return true on ERR, return false on OK)

which one would be more efficient?
 
Last edited:
Whichever's more efficient depends on the rest of your code. That's probably the second one so you can say if it's bad error - otherwise continue.
 
Back
Top