How to validate Hex color code with regular expression

Hexadecimal Color Code Regular Expression Pattern


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

Description


^		 #start of the line
 #		 #  must constains a "#" symbols
 (		 #  start of group #1
  [A-Fa-f0-9]{6} #    any strings in the list, with length of 6
  |		 #    ..or
  [A-Fa-f0-9]{3} #    any strings in the list, with length of 3
 )		 #  end of group #1 
$		 #end of the line

Whole combination is means, string 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. This regular expression pattern is very useful for the Hexadecimal web colors code checking.

Java Regular Expression Example


package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class HexValidator{
	
   private Pattern pattern;
   private Matcher matcher;
 
   private static final String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
	        
   public HexValidator(){
	  pattern = Pattern.compile(HEX_PATTERN);
   }
	  
   /**
   * Validate hex with regular expression
   * @param hex hex for validation
   * @return true valid hex, false invalid hex
   */
   public boolean validate(final String hex){
		  
	  matcher = pattern.matcher(hex);
	  return matcher.matches();
	    	    
   }
}

Hex code that match:

1. “#1f1f1F”, “#AFAFAF”,”#1AFFa1″,”#222fff”, “#F00”, “#F00”

Hex code that doesn’t match:

1. “123456” – must start with a “#” symbol
2. “#afafah” – “h” is not allow, valid letter from “a” to “f”
3. “#123abce” – either 6 length or 3 length
4. “aFaE3f” – must start with a “#” symbol, either 6 length or 3 length
5. “F00” – must start with a “#” symbol
6. “#afaf” – either 6 length or 3 length
7. “#F0h” – “h” is not allow, valid letter from “a” to “f”

Unit Test – HexValidator


package com.mkyong.regex;

import org.testng.Assert;
import org.testng.annotations.*;
 
/**
 * Hex validator Testing
 * @author mkyong
 *
 */
public class HexValidatorTest {
 
	private HexValidator hexValidator;
    
	@BeforeClass
        public void initData(){
		hexValidator = new HexValidator();
        }
    
	@DataProvider
	public Object[][] ValidHexProvider() {
		return new Object[][]{
			   {new String[] {
				"#1f1f1F", "#AFAFAF","#1AFFa1","#222fff", "#F00"
			   }}
		};
	}
	
	@DataProvider
	public Object[][] InvalidHexProvider() {
		return new Object[][]{
			{new String[] {
				   "123456","#afafah","#123abce","aFaE3f",
				   "F00","#afaf", "#F0h"	 
		        }}
		};
	}
	
	@Test(dataProvider = "ValidHexProvider")
	public void ValidHexTest(String[] hex) {
		
	   for(String temp : hex){
		   boolean valid = hexValidator.validate(temp);
		   System.out.println("Hex is valid : " + temp + " , " + valid);
		   Assert.assertEquals(true, valid);
	   }
	   
	}
	
	@Test(dataProvider = "InvalidHexProvider", dependsOnMethods="ValidHexTest")
	public void InValidHexTest(String[] hex) {
		
	   for(String temp : hex){
		   boolean valid = hexValidator.validate(temp);
		   System.out.println("Hex is valid : " + temp + " , " + valid);
		   Assert.assertEquals(false, valid);
	   }
	   
	}
}

Unit Test – Result


Hex is valid : #1f1f1F , true
Hex is valid : #AFAFAF , true
Hex is valid : #1AFFa1 , true
Hex is valid : #222fff , true
Hex is valid : #F00 , true
Hex is valid : 123456 , false
Hex is valid : #afafah , false
Hex is valid : #123abce , false
Hex is valid : aFaE3f , false
Hex is valid : F00 , false
Hex is valid : #afaf , false
Hex is valid : #F0h , false
PASSED: ValidHexTest([Ljava.lang.String;@1a626f)
PASSED: InValidHexTest([Ljava.lang.String;@e5855a)

===============================================
    com.mkyong.regex.HexValidatorTest
    Tests run: 2, Failures: 0, Skips: 0
===============================================


===============================================
mkyong
Total tests run: 2, Failures: 0, Skips: 0
===============================================

Reference

http://en.wikipedia.org/wiki/Web_colors

Want to learn more about regular expression? Highly recommend this best and classic book – “Mastering Regular Expression”



About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Guest
Guest
Guest
Small typo in the example? I know nothing of these, but i think your explanation should be changed from: “Whole combination is means, string 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. This regular expression pattern is very useful for the Hexadecimal web colors code checking” to “Whole combination is means, string must start with a “#” symbol , follow by a letter from “a” to “f”, “A” to “F” or a digit from “0? to 9?… Read more »
trackback
Java Regular Expression Tutorials | J2EE Web Development Tutorials

[…] Hex color code regular expression Hex color code regular expression example in Java and unit tested with TestNG. ^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$ […]

Berry
Guest
Berry

Shorter (Byte-wise):
^#([0-9a-fA-F]{3}){1,2}$

More readable (But 1 byte more):
^#([[:xdigit:]]{3}){1,2}$

Barthy B.
Guest
Barthy B.

Thanks a lot for this code snippet! grat job :-)

André
Guest
André

Yes, just A-F, a-f, because of HEX :-)

trackback
10 Java Regular Expression Examples You Should Know | Regular Expressions

[…] ==> See the explanation and example here […]