Java regex hex color code
This article shows how to use regex to validate a hex color code.
Regex for hex color code.
^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$
Regex explanation
^ # start of the line
# # start with a number sign `#`
( # start of (group 1)
[a-fA-F0-9]{6} # support z-f, A-F and 0-9, with a length of 6
| # or
[a-fA-F0-9]{3} # support z-f, A-F and 0-9, with a length of 3
) # end of (group 1)
$ # end of the line
1. Hexadecimal color code format.
In web, we can use RGB triplet or hex triplet (hex color code) to represents colors on a web page. For the hex color code, there are two formats, a standard hex triplet and shorthand hex format, both formats start with a leading number sign #
.
1.1 Hex Triplet Forma
The hex triplet or standard hex color code uses six (hexadecimal)-digit form to represent color. For examples:
#000000
#FFFFFF
#808080
#8A2BE2
For #8A2BE2
, the first hex 8A
represents red value, the second 2B
represents green value, and the third E2
represents blue value.
1.2 Shorthand Hex Format
The Shorthand hex uses three (hexadecimal)-digit form to represents a color. The idea is merely doubling each digit to become the above hex triplet format. For examples:
#000
#FFF
#09C
For #000
, it will become #000000
. For #09C
, it will become #0099CC
.
Read the below CSS syntax; both represent the same color.
p { color: #000; } /* black color, hex triplet format */
h1 { color: #000000; } /* same color as above, shorthand hex format */
Web Color
For more information, please read this Wikipedia – Web Color.
2. Java regex to validate hex color code
Below is a Java regex example to validate hex color code in standard hex triplet and shorthand formats.
package com.mkyong.regex.hex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HexValidatorWebColor {
private static final String HEX_WEBCOLOR_PATTERN
= "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$";
private static final Pattern pattern = Pattern.compile(HEX_WEBCOLOR_PATTERN);
public static boolean isValid(final String colorCode) {
Matcher matcher = pattern.matcher(colorCode);
return matcher.matches();
}
}
3. Tests for the regex hex color code.
Below are the unit tests to validate a list of valid and invalid hex color codes.
package com.mkyong.regex.hex;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class HexValidatorWebColorTest {
@ParameterizedTest(name = "#{index} - Run test with web color = {0}")
@MethodSource("validWebColorProvider")
void test_color_regex_valid(String color) {
assertTrue(HexValidatorWebColor.isValid(color));
}
@ParameterizedTest(name = "#{index} - Run test with web color = {0}")
@MethodSource("invalidWebColorProvider")
void test_color_regex_invalid(String color) {
assertFalse(HexValidatorWebColor.isValid(color));
}
static Stream<String> validWebColorProvider() {
return Stream.of(
"#000000",
"#999999",
"#1a1a1a",
"#1A1A1A",
"#0f0f0f",
"#0F0F0F",
"#bcbcbc",
"#BcbCbC",
"#000",
"#FFF",
"#abc",
"#def");
}
static Stream<String> invalidWebColorProvider() {
return Stream.of(
"123456", // must start with a #
"#afafah", // support a-f only, h is not allowed
"#123abce", // invalid length, must length of 3 or 6
"#1234", // invalid length, must length of 3 or 6
"#-123", // support 0-9 only
" ", // space
""); // empty
}
}
4. Regex find hex color code from a String
Below is an example of using regex to find or extract a hex color code from a String.
package com.mkyong.regex.hex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindHexColorCode {
public static void main(String[] args) {
String str = "p { color: #000; }";
Pattern pattern = Pattern.compile(
"^(.*?)(#([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))\\b(.*)$");
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
System.out.println(matcher.groupCount()); // 4
System.out.println(matcher.group(0)); // p { color: #000; }
System.out.println(matcher.group(1)); // p { color:
System.out.println(matcher.group(2)); // #000
System.out.println(matcher.group(3)); // 000
System.out.println(matcher.group(4)); // ; }
} else {
System.out.println("no match!");
}
}
}
Output
4
p { color: #000; }
p { color:
#000
000
; }
In regex, the \b
metacharacter means word boundry, which ensures the hex color code is not followed by any words.
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-regex/hex
Shorter (Byte-wise):
^#([0-9a-fA-F]{3}){1,2}$
More readable (But 1 byte more):
^#([[:xdigit:]]{3}){1,2}$
Thanks a lot for this code snippet! grat job 🙂
Yes, just A-F, a-f, because of HEX 🙂