Friday, February 11, 2011

Yahoo Username Regex

I need a (php) regex to match Yahoo's username rules:

Use 4 to 32 characters and start with a letter. You may use letters, numbers, underscores, and one dot (.).

  • A one dot limit? That's tricky.

    I'm no regex expert, but I think this would get it, except for that:

    [A-Za-z][A-Za-z0-9_.]{3,31}
    

    Maybe you could check for the . requirement separately?

  • /[a-zA-Z][a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*/
    

    And check if strlen($username) >= 4 and <= 32.

    Joel Coehoorn : Now if we could find a way to combine these, just that it MUST match both.
    Randy : Yeah. strlen is a pretty quick operation, though.
    magicrobotmonkey : but i dont have a chance to use strlen, in the spot I'm at, one regex is all I get.
    Randy : What's preventing you from adding a line after the regex?
    Joel Coehoorn : lots of things could. In ASP.Net, for example, you could be using a RegExValidator control. Or he might have a line in a config file he gets to set and that's it.
    magicrobotmonkey : yea its pretty much the latter. I'm trying to keep my class nice and clean.
    Randy : If you want to keep it to one line in that one location, you can always turn this into a checkusername() function and do the two checks there. Trying to keep classes clean sounds like it's going to leave you with unmaintainable code if you're constantly trying to find ways to combine lines.
    From Randy
  • Using lookaheads you could do the following:

    ^(?=[A-Za-z](?:\w*(?:\.\w*)?$))(\S{4,32})$
    

    Because you didn't specify what type of regex you needed I added a lot of Perl 5 compatible stuff. Like (?: ... ) for non-capturing parens.

    Note: I added the missing close paren back in.

    magicrobotmonkey : This one's missing a closing paren, and once i add it (tried a couple places...) I can't get it to match any strings i throw at it.
    From Axeman
  • /^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/
    
    magicrobotmonkey : initial testing seems to confirm this one works. I;m not sure why...
    magicrobotmonkey : ok after reading about lookarounds, i get it now, thats pretty sick man, thanks
    From MizardX

0 comments:

Post a Comment