CodesJava

Easy learning with example program codes

java regex pattern validate username


Regular expressions

Regular expressions represents a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. The abbreviation for regular expression is regex. In programming regular expressions are mainly used to define constraint on strings like password, email validation.

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.codesjava;
 
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
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki