Tutorialspoint examples

Learn java tutorial with examples for beginners online

java regex pattern validate hex code


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.

#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

This regular expression refers to a pattern which must start with a “#” symbol, follow by a letter from “a” to “f”, “A” to “Z” or a digit from “0” to 9″ with exactly 6 or 3 length.

Example

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 = 
			"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,15})";
	public static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	
		values.add("jaisingh1A@"); 
		values.add("Sjai12$"); 
		values.add("jaiA@");
		values.add("jai*");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
		  if(matcher.matches()){
			  System.out.println("Password "+ value +" is valid");
		  }else{
			  System.out.println("Password "+ value +" is invalid");
		  }		  
		}
	}
}

Output

Password jaisingh1A@ is valid
Password Sjai12$ is valid
Password jaiA@ is invalid
Password jai* is invalid
Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status