Quick Modification of Username RegEx

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Kev
Forum Newbie
Posts: 21
Joined: Tue Aug 25, 2009 9:11 pm

Quick Modification of Username RegEx

Post by Kev »

Hi guys,

I found a regEx online for matching a username, allowing spaces and such. But the regEx pattern has no limits on the character length of the string it should match. I want usernames to be between 3 and 15 characters. How can I modify this regular expression to apply this character length limitation on the username?

Code: Select all

^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$
Thanks for any help and guidance!

Kev
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Quick Modification of Username RegEx

Post by ridgerunner »

This one does what you want. It matches a username from 3 to 15 characters long that must begin and end with an alphanumeric and may have multiple words separated by a single dash, underscore or space:

Code: Select all

if (preg_match('/^(?:[A-Za-z0-9]|(?<=[A-Za-z0-9])[ _-](?=[A-Za-z0-9])){3,15}$/', $text)) {
    # Successful match
} else {
    # Match attempt failed
}
Regards from Salt Lake City
User avatar
Kev
Forum Newbie
Posts: 21
Joined: Tue Aug 25, 2009 9:11 pm

Re: Quick Modification of Username RegEx

Post by Kev »

Hi RidgeRunner,

Thanks so much for your help. Althought I've tried pasting your regular expression into RegExPal (http://regexpal.com/) and it doesn't match anything. Is there something I'm missing here?

Since posting this last night, I've done some reading on RegEx and learned about positive lookahead assertions and altered my previous regular expression to this:

Code: Select all

^(?=[A-Za-z0-9 -_]{3,15}$)[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$
This seems to work nicely. Since I don't have experienced RegEx eyes, can you take a look at it and let me know if you see any flaws? Thanks so much!
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Quick Modification of Username RegEx

Post by ridgerunner »

The online regex tester that you are using is only good for the JavaScript regex flavor which does not support lookbehind. The regex I provided uses look behind so will not work with JavaScript, but it will work just fine with PHP scripts (which is what this website is dedicated to).

That said, your modified regex looks A-Ok to me. Nice job.

Edit 2009-09-17: Upon closer inspection, your new regex can be shortened a bit (the lookahead only cares about the count, so the dot can be used instead of the character class). Like so:

Code: Select all

^(?=.{3,15}$)[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$
Post Reply