John McMullen
John McMullen

Reputation: 77

username regex alphanumeric with underscore only

I'm trying to find a regex expression for php's preg_match that allows alphanumeric characters, with underscores, but the underscore MUST be between characters (not on beginning or end of string), and there can never be 2 underscores next to each other.

Examples:

INVALID:

_name
na_me_
na__me

VALID:

na_me
na_m_e

The one i've found works for most parts of this, but doesn't protect against repeated underscores is:

/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/

But like I said, that still allows for cases like na__me.

Anyone have any ideas? Thanks!

Upvotes: 2

Views: 2235

Answers (3)

Ruud Helderman
Ruud Helderman

Reputation: 11018

Yours looks fine. As does this one, which is a bit shorter:

/^[a-z](?:_?[a-z0-9])*$/i

Upvotes: 1

Alexander
Alexander

Reputation: 632

If you want REGEX to handle a specific length of characters, you use { and }

ex.

[a-z]{2,4}

Will return all strings of lowercase letters of length 2, 3, and 4.

In your case you would use {0,1} to signify that NO or 1 underscores are acceptable.

Upvotes: 0

tchrist
tchrist

Reputation: 80423

This will do it:

(?x)           # enable comments and whitespace to make
               # it understandable.  always always do this.

^              # front anchor

[\pL\pN]       # an alphanumeric

# now begin a repeat group that 
# will go through the end of the string

(?: [\pL\pN]   # then either another alnum
  |            # or else an underbar surrounded
               # by an alnum to either side of it
    (?<= [\pL\pN] )      # must follow an alnum behind it
    _                    # the real underscore
    (?=  [\pL\pN] )      # and must precede an alnum before it
) *            # repeat that whole group 0 or more times

\z             # through the true end of the string

So you start off with an alphanumeric, then have any number of alphanumunders through the end, constraining any actual underscores to be surround by an actual alphanumerics to either side.

Upvotes: 5

Related Questions