Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for username

Tags:

regex

I need help on regular expression on the condition (4) below:

  1. Begin with a-z
  2. End with a-z0-9
  3. allow 3 special characters like ._-
  4. The characters in (3) must be followed by alphanumeric characters, and it cannot be followed by any characters in (3) themselves.

Not sure how to do this. Any help is appreciated, with the sample and some explanations.

like image 487
neobie Avatar asked May 17 '10 05:05

neobie


Video Answer


2 Answers

You can try this:

^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$

This uses lookaheads to enforce that username must have between 5 and 10 characters (?=.{5,10}$), and that none of the 3 special characters appear twice in a row (?!.*[._-]{2}), but overall they can appear any number of times (Konrad interprets it differently, in that the 3 special characters can appear up to 3 times).

Here's a test harness in Java:

    String[] test = {
        "abc",
        "abcde",
        "acd_e",
        "_abcd",
        "abcd_",
        "a__bc",
        "a_.bc",
        "a_b.c-d",
        "a_b_c_d_e",
        "this-is-too-long",
    };
    for (String s : test) {
        System.out.format("%s %B %n", s,
            s.matches("^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$")
        );
    }

This prints:

abc FALSE 
abcde TRUE 
acd_e TRUE 
_abcd FALSE 
abcd_ FALSE 
a__bc FALSE 
a_.bc FALSE 
a_b.c-d TRUE 
a_b_c_d_e TRUE 
this-is-too-long FALSE 

See also

  • regular-expressions.info/Lookarounds, limiting repetitions, and anchors
like image 169
polygenelubricants Avatar answered Sep 28 '22 06:09

polygenelubricants


So basically:

  1. Start with [a-z].
  2. Allow a first serving of [a-z0-9], several times. 1)
  3. Allow
    • at most one of [._-], followed by
    • at least one of [a-z0-9]
    • three times or less.
  4. End with [a-z0-9] (implied in the above).

Which yields:

^[a-z][a-z0-9]*([._-][a-z0-9]+){0,3}$

But beware that this may result in user names with only one character.


1) (posted by @codeka)

like image 37
Konrad Rudolph Avatar answered Sep 28 '22 06:09

Konrad Rudolph