Tutorialspoint examples

Learn java tutorial with examples for beginners online

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.


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


package com.tutorialspointexamples;
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>();	       
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
			  System.out.println("Username "+ value +" is valid");
			  System.out.println("Username "+ value +" is invalid");


Username Jai_singh is invalid
Username Jai@5 is invalid
Username jai12345 is valid
Username jai_singh is valid
Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status