java regex pattern validate username

Regular expression username pattern

^[a-z0-9_-]{5,15}$

This regular expression refers to a pattern which accepts 5 to 15 characters with any lower case character, digit or special symbol “_-” only.

Example

package com.w3spoint;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexTest {
	private static final String PATTERN = "^[a-z0-9_-]{5,15}$";
	public static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	       
		values.add("Jai_singh"); 
		values.add("Jai@5"); 
		values.add("jai12345");
		values.add("jai_singh");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
		  if(matcher.matches()){
			  System.out.println("Username "+ value +" is valid");
		  }else{
			  System.out.println("Username "+ value +" is invalid");
		  }		  
		}
	}
}

Output

Username Jai_singh is invalid
Username Jai@5 is invalid
Username jai12345 is valid
Username jai_singh is valid
Content Protection by DMCA.com
Please Share