Regular expression to validate username

125,110

Solution 1

^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$
 └─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘
       │         │         │            │           no _ or . at the end
       │         │         │            │
       │         │         │            allowed characters
       │         │         │
       │         │         no __ or _. or ._ or .. inside
       │         │
       │         no _ or . at the beginning
       │
       username is 8-20 characters long

If your browser raises an error due to lack of negative look-behind support, use the following alternative pattern:

^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$

Solution 2

I guess you'd have to use Lookahead expressions here. http://www.regular-expressions.info/lookaround.html

Try

^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$

[a-zA-Z0-9] an alphanumeric THEN (

_(?!\.) a _ not followed by a . OR

\.(?!_) a . not followed by a _ OR

[a-zA-Z0-9] an alphanumeric ) FOR

{6,18} minimum 6 to maximum 18 times THEN

[a-zA-Z0-9] an alphanumeric

(First character is alphanum, then 6 to 18 characters, last character is alphanum, 6+2=8, 18+2=20)

Solution 3

As much as I love regular expressions I think there is a limit to what is readable

So I would suggest

new Regex("^[a-z._]+$", RegexOptions.IgnoreCase).IsMatch(username) &&
!username.StartsWith(".") &&
!username.StartsWith("_") &&
!username.EndsWith(".") &&
!username.EndsWith("_") &&
!username.Contains("..") &&
!username.Contains("__") &&
!username.Contains("._") &&
!username.Contains("_.");

It's longer but it won't need the maintainer to open expresso to understand.

Sure you can comment a long regex but then who ever reads it has to rely on trust.......

Solution 4

A slight modification to Phillip's answer fixes the latest requirement

^[a-zA-Z0-9]([._](?![._])|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$

Solution 5

private static final Scanner scan = new Scanner(System.in);

public static void main(String[] args) {
    int n = Integer.parseInt(scan.nextLine());
    while (n-- != 0) {
        String userName = scan.nextLine();
        String regularExpression = "^[[A-Z]|[a-z]][[A-Z]|[a-z]|\\d|[_]]{7,29}$";
        if (userName.matches(regularExpression)) {
            System.out.println("Valid");
        } else {
            System.out.println("Invalid");
        }
    }
}
Share:
125,110
mohsen dorparasti
Author by

mohsen dorparasti

passionate about creating new things I am.

Updated on July 08, 2022

Comments

  • mohsen dorparasti
    mohsen dorparasti almost 2 years

    I'm trying to create a regular expression to validate usernames against these criteria:

    1. Only contains alphanumeric characters, underscore and dot.
    2. Underscore and dot can't be at the end or start of a username (e.g _username / username_ / .username / username.).
    3. Underscore and dot can't be next to each other (e.g user_.name).
    4. Underscore or dot can't be used multiple times in a row (e.g user__name / user..name).
    5. Number of characters must be between 8 to 20.

    This is what I've done so far; it sounds it enforces all criteria rules but the 5th rule. I don't know how to add the 5th rule to this:

     ^[a-zA-Z0-9]+([._]?[a-zA-Z0-9]+)*$
    
  • Adam Wolski
    Adam Wolski almost 12 years
    Try: ^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-z‌​A-Z0-9]$
  • ridgerunner
    ridgerunner almost 12 years
    Yup, this one works. But the (_|\.) expression can be streamlined to just [_.].
  • ridgerunner
    ridgerunner almost 12 years
    Nice one. But you may want to look into using free-spacing mode and embed your comments right in there with the code. +1
  • Ωmega
    Ωmega almost 12 years
    @ridgerunner - I believe this way it is easy to read and port to code.
  • vignesh kumar
    vignesh kumar almost 9 years
    @Ωmega can we use [\w\.] instead of [a-zA-Z0-9._]
  • Ωmega
    Ωmega almost 9 years
    @vigneshkumar - same meaning, but [a-zA-Z0-9._] is easy to read and understand
  • Jackson Lenhart
    Jackson Lenhart over 7 years
    the < in (?<![_.])$ causes a parsing error for me "invalid regular expression"
  • Ωmega
    Ωmega over 7 years
    @JacksonLenhart - What regex engine and programming language you use? Please note this question was tagged with asp.net tag and while the answer is valid for most of other languages and engines, not all support negative lookahead and lookbehind zero-length assertions.
  • Jackson Lenhart
    Jackson Lenhart over 7 years
    Ah yes, I was naive enough to think regex would be the same for all languages. I'm using javascript (es6), no additional regex engine
  • Toto
    Toto over 4 years
    This is allowing underscore at the beginning and at the end, which is not wanted.
  • Toto
    Toto over 4 years
    It also matches infinite length string that contains only underscore.
  • FrEqDe
    FrEqDe over 4 years
    @Toto, I fixed it.
  • Karan Jagtiani
    Karan Jagtiani over 4 years
    Please note that this regular expression causes an Angular app to crash on IOS devices, as well as on the Firefox browser.
  • ElRey777
    ElRey777 over 4 years
    For those who will use this in JS: this RegEx works great in Chrome. But it raises an error in Safari, Firefox, Edge, etc.
  • ElRey777
    ElRey777 over 4 years
    Nice, if somebody need such a RegEx for JS, this is the way. It works in all browsers unlike the most voted answer that's Chrome-only
  • user229044
    user229044 over 4 years
    Firefox considers this regex to be a syntax error, and produces SyntaxError: invalid regexp group.
  • Ibrahim Azhar Armar
    Ibrahim Azhar Armar almost 4 years
    This gives issue in character limit rule, with the given rule of {6,18} it accepts min 8 characters whereas it must be accepting 6, If I make it {4,18} then it will accept 6 characters whereas I have defined 4
  • Eazy
    Eazy about 3 years
    Works fine, but allows - character, I made a little adjustment to it here: ^(?=.{4,20}$)(?:[a-zA-Z\d]+(?:[._][a-zA-Z\d])*)+$ which fix it for me, thanks for the code @FrEqDe
  • Admin
    Admin over 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
  • theProCoder
    theProCoder over 2 years
    wow, that is very helpful that you specified the sections. thanks so much
  • Richardd
    Richardd over 2 years
    Thanks @Ωmega It seems that also run in Flutter for android. I did not tested on ios.