Regex for Hex Color Code
Matches 3 or 6 digit hex color codes.
Understanding The Regex Pattern
/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/- #FFF
- #000000
- #a3f
- #ZZZ
- #1234
- 123456
How this Pattern Works
Hexadecimal color codes are the absolute standard format for representing exact colors in web development, CSS stylesheets, SVG illustrations, and digital graphics software. This specific regular expression accurately matches valid hex color strings, ensuring they always begin with a hash (#) symbol. It then verifies that the hash is immediately followed by either exactly 3 or exactly 6 valid hexadecimal characters (which include the numbers 0-9 and the letters A-F, in both uppercase and lowercase formats).
Validating hex codes is a particularly critical feature when building custom design tools, dynamic theme generators, user profile customization interfaces, and CSS parsers. The 3-character variant is a standard CSS shorthand (where '#FFF' expands to '#FFFFFF'), and this pattern correctly accounts for both lengths while rejecting invalid lengths like 4 or 5 characters which would cause rendering failures.
Implementing this regular expression ensures that any user-customized colors will render beautifully and correctly across all modern web browsers. Furthermore, it acts as a preventative measure, stopping invalid or malformed CSS values from being injected into your stylesheets, which could otherwise silently break a page's layout, corrupt the visual design of an application, or result in unpredictable UI behavior for the end user.
Implement The Regex In Your Code
const regex = /^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
regex.test('#FFFFFF');import re
regex = re.compile(r'^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$')
bool(regex.match('#FFFFFF'))import "regexp"
matched, _ := regexp.MatchString(`^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$`, "#FFFFFF")use regex::Regex;
let re = Regex::new(r"^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$").unwrap();
re.is_match("#FFFFFF")