RegexBuilder · regex answers
Regex for a hex colour code
/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/iCSS accepts four lengths: three digits, four with alpha, six, and eight with alpha. Ordering the alternatives longest-first is unnecessary here because the anchors force a full-string match, but it matters the moment you drop the $.
What each part does
| # | the literal hash |
| [0-9a-f]{3} | shorthand, one hex digit per channel |
| [0-9a-f]{8} | full form with an alpha channel |
| i | case-insensitive — #FFF and #fff are the same colour |
Tested against real input
Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.
| Input | Result | Matched |
|---|---|---|
| #fff | matches | #fff |
| #FFFF | matches | #FFFF |
| #a1b2c3 | matches | #a1b2c3 |
| #a1b2c3ff | matches | #a1b2c3ff |
| fff | no match | — |
| #ff | no match | — |
| #12345 | no match | — |
| #gggggg | no match | — |
The mistake to avoid
Writing ^#[0-9a-f]{3,8}$ — that also accepts five and seven digits, which no browser understands.
Try it on your own text
Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.
Open RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID