How to Validate Hex Color Code in Java


In this example we will show how to validate Hex color code with regular expression in Java.

Source Code

package com.beginner.examples;

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

public class ValidateHexColor {

	public static void main(String[] args) {
		
		String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
		
		Pattern pattern = Pattern.compile(HEX_PATTERN);;
		Matcher matcher = pattern.matcher("afafah");
		Matcher matcher2 = pattern.matcher("#1f1f1F");
		System.out.println(matcher.matches());
		System.out.println(matcher2.matches());

	}
}

Output:

false
true

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

How to Validate Hex Color Code in Java


In this example, let’s see how to validate Hex color code with regular expression in Java.

Source Code

package com.beginner.examples;

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

public class ValidateHexColor {

	public static void main(String[] args) {
		
		String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
		
		Pattern pattern = Pattern.compile(HEX_PATTERN);;
		Matcher matcher = pattern.matcher("afafah");
		Matcher matcher2 = pattern.matcher("#1f1f1F");
		System.out.println(matcher.matches());
		System.out.println(matcher2.matches());

	}
}

Output:

false
true

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments