CodesJava

Easy learning with example program codes

java regex validate alphanumeric


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 to accept alphanumeric only

^[a-zA-Z0-9]+$

This regular expression refers to a pattern which accepts all lower and upper case characters, and digits 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-zA-Z0-9]+$";
	public static void main(String args[]){ 
		List<String> names = new ArrayList<String>();	       
		names.add("Jai"); 
		names.add("Jai12"); 
		names.add("Jai12-");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String name : names){
		  Matcher matcher = pattern.matcher(name);
		  System.out.println(matcher.matches());
		}
	}
}

Output

true
true
false


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap