How to Validate User Name Using Regular Expression in Java


In this example we will show how to validate user name using regular expression. You can first to compile the regular string into the Pattern object, obtain the matcher of the specified string from the Pattern object, and then use the matcher to make judgment.You can also use the matches() method on the String object to determine if the user name is legitimate.

Source Code

– VerifyUsernameExample0

package com.beginner.examples;

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

public class VerifyUsernameExample0 {

	public static void main(String[] args) {
		
		String user1 = "Tom123";
		String user2 = "Jerry";
		
		Pattern pattern  = Pattern.compile("[dw_]{6,13}");
		
		//Gets the matcher from the specified string
		Matcher matcher1 = pattern.matcher(user1);
		
		System.out.println(user1+" : "+matcher1.matches());
		
		
		////Gets the matcher from the specified string
		Matcher matcher2 = pattern.matcher(user2);
		
		System.out.println(user2+" : "+matcher2.matches());
		
	}
}

– VerifyUsernameExample

package com.beginner.examples;

public class VerifyUsernameExample {

	public static void main(String[] args) {
		
		//Define regular string
		String reg = "[wd]{6,13}";
		
		String username1 ="Tom123";
		
		String username2 = "Jerry";
		 
		//Verify using the matches() method in the String object
		System.out.println(username1+" : "+username1.matches(reg));
		
		System.out.println(username2+" : "+username2.matches(reg));
		
	}

}

Output:

Tom123 : true
Jerry : false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments