Regex for username

I want to create a method in java to validate username using Regex. But I am not very good at creating Regex and it is difficult. I would appreciate any of your kind help - suggestions

I want usernames to follow these rules:

  • No more than 9 characters
  • At least 3 characters
  • No special characters other than underscore and hyphen ("_" and "-")
  • These two characters cannot be next to each other, and the username cannot start or end with them.

I only know how to apply rule no. 3

String Regex = "^[\w-]+$";

      

NOTE. rules 1.and 2. are not important for regex because I will probably do these checks with java. But I would like to know how to do it.

+3


source to share


2 answers


Walk by your own rules:

  • No more than 9 characters
  • At least 3 characters

The two can be grouped into a quantifier {3,9}

that applies to your entire username. You are already using a quantifier +

, which means "one or more", you can remove it.

"^[\w\s-]{3,9}$"

      


  1. No special characters other than underscore and hyphen ("_" and "-")

You've already covered this, but note what the \s

spaces mean. You don't mention spaces in your question, are you sure you need it?


  1. These two characters cannot be one after the other, and the username cannot begin or end with them.

This is where it gets more complicated. You need search statements to enforce these rules one by one.



First, let's start with "These two characters cannot be next to each other." You can use a negative expression in front of your regex, which checks that the two are not concatenated anywhere:

(?!.*[-_]{2,})

      

?!

means "the upcoming line must not match the next regex" (aka negative lookahead), but [-_]{2,}

means "two or more underscores / dashes".

The next part of the rule is "can't start or end with them." We could create two separate negative mappings for this (not starting and ending with these characters), but as pointed out in the comments, you can also combine them into one positive result:

(?=^[^-_].*[^-_]$)

      

This means that the upcoming line should (positive) match "no" or "_", then any number of characters, then no again - or _ ".


Combine all of these views with the original regex and you have the answer:

"^(?!.*[-_]{2,})(?=^[^-_].*[^-_]$)[\w\s-]{3,9}$"

      

You can use this tool to check if a regex matches multiple inputs if it works correctly: http://www.regexplanet.com/advanced/java/index.html

+7


source


[A-Za-z0-9_-]  # a number or letter or underscore or hyphen
{3,9}          # Length at least 3 characters and maximum length of 15
^(?![_-]).     # can't start with underscore or hyphen
(?<![-_])$     # can't end with underscore or hyphen
((?!_-|-_).)   # underscore and hyphen can't be the one after the other

      

So

 ^(?![_-]).[A-Za-z0-9_-]((?!_-|-_).)(?<![-_]){3,9}$

      

Simple demo:



package example;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Validator{

      private  Pattern pattern;
      private  Matcher matcher;

      private static final String USERNAME_PATTERN = 
              "^(?![_-]).[A-Za-z0-9_-]((?!_-|-_).)(?<![-_]){3,9}$";

      public Validator(){
          pattern = Pattern.compile(USERNAME_PATTERN);
      }

      /**
       * Validate username with regular expression
       * @param username username for validation
       * @return true valid username, false invalid username
       */
      public  boolean validate(final String username){

          matcher = pattern.matcher(username);
          return matcher.matches();

      }
}

public class UserNameValidator {
    public static void main(String[] args) {
          Validator v = new Validator();
          System.out.println(v.validate("cd-eh"));
      }

}

      

Output:

true

      

+2


source







All Articles