java regex pattern validate hex code

Regular expression hex code pattern


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.


package com.w3spoint;
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 = 
	public static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	
		values.add("[email protected]"); 
		values.add("[email protected]");
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
			  System.out.println("Password "+ value +" is valid");
			  System.out.println("Password "+ value +" is invalid");


Password [email protected] is valid
Password Sjai12$ is valid
Password [email protected] is invalid
Password jai* is invalid
Content Protection by
Please Share