Page 1 of 1

a simple regex question

Posted: Sun Sep 02, 2007 8:56 am
by beemzet
Hi all,

Could you help me out here plz?

I want to validate a username with regular expressions, where username can begin with letters or numbers, and it may follow with the only underscore(_) and/or the only dot(.). Finally username should end with letters or numbers.


Ex:
Valid user names:
hello_world
HELLO.World
hello.beautiful_world

Invalid usernames:
hello__world
HELLO..World
hello._beautiful_.world

btw, underscore and dot orders are not important. What i mean is, first may come an underscore, then a dot. Or the other way around.

Could you write the code with preg_match, plz?

Thank you.

Posted: Sun Sep 02, 2007 11:24 am
by vigge89
Reading your post, it almost sounds like you only want to allow a maximum of one underscore and/or period, am I right?
If not:

Code: Select all

if (!preg_match("#^[a-z0-9]+([._][a-z0-9]+)?$#i", $username)):
    // username is not valid
endif;
Also, there's an regex forum dedicated to questions regarding regular expressions. I suggest you post any future questions of this sort there ;)

Posted: Sun Sep 02, 2007 12:11 pm
by John Cartwright
Moved to Regex.

Posted: Sun Sep 02, 2007 7:07 pm
by beemzet
vigge89 wrote:Reading your post, it almost sounds like you only want to allow a maximum of one underscore and/or period, am I right?
If not:

Code: Select all

if (!preg_match("#^[a-z0-9]+([._][a-z0-9]+)?$#i", $username)):
    // username is not valid
endif;
Also, there's an regex forum dedicated to questions regarding regular expressions. I suggest you post any future questions of this sort there ;)
Thanx for your reply!

But I think it is not working properly.
For example, hello.beautiful_world is supposed to be a valid username, but your code says its invalid.

Any other suggestions?

Posted: Mon Sep 03, 2007 12:44 pm
by vigge89
Woops, mistake (switch ? for *):

Code: Select all

if (!preg_match("#^[a-z0-9]+([._][a-z0-9]+)*$#i", $username)):
    // username is not valid
endif;

Posted: Tue Sep 04, 2007 9:53 am
by GeertDD
vigge89 wrote:

Code: Select all

if (!preg_match("#^[a-z0-9]+([._][a-z0-9]+)*$#i", $username)):
    // username is not valid
endif;
Watch out for exponential matching. Things can really be sped up by using possessive quantifiers:

Code: Select all

#^[a-z0-9]++([._][a-z0-9]++)*$#i

Posted: Tue Sep 04, 2007 12:25 pm
by vigge89
Just looked possesive quantifiers up as I've never used it (or seen it) before, cheers for that :)