PDA

View Full Version : RegEx help



Agum
April 30th, 2007, 23:55
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?

themoose
May 1st, 2007, 11:26
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.