Username regex

I need help with regular expression provided (4) below:

  • Start with az
  • Finish with a-z0-9
  • allow 3 special characters ._-
  • The characters in (3) must be accompanied by alphanumeric characters, which cannot be followed by any characters in (3).

I don’t know how to do it. Any help is appreciated with a sample and some clarifications.

+5
source share
4 answers

try the following:

^[a-zA-Z](([\._\-][a-zA-Z0-9])|[a-zA-Z0-9])*[a-z0-9]$

1) ^ [a-zA-Z]: start

2) (([._-] [a-zA-Z0-9]) | [a-zA-Z0-9]) *: any number in either the alphabet or special char, followed by alphanum

3) [a-z0-9] $

+5
source

You can try the following:

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

lookaheads , 5 10 (?=.{5,10}$), (?!.*[._-]{2}), ( -, 3 ).

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]$")
        );
    }

:

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 

.

+9

, :

  • [a-z].
  • [a-z0-9] . 1)
    • [._-],
    • [a-z0-9]
    • .
  • [a-z0-9] ( ).

:

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

, .


1) ( @codeka)

+7

, ... . Regex - , . nqueens. ( , , .)

function valid(n) {
  return (n.length > 3
    && n.match(/^[a-z]/i)
    && n.match(/[a-z0-9]$/i)
    && !n.match(/[._-]{2}/)
}

Now imagine that you allow only one thing., _ Or - of everything (maybe I misunderstood the initial requirements of shrug); which is easy to add (and visualize):

&& n.replace(/[^._-]/g, "").length <= 1

And before someone says “which is less effective,” go through it in the intended use. Also note: I have not given up using regexes completely, they are wonderful things.

+1
source

All Articles