# Regex for Hex Color Codes

> Hex color regex matching #fff and #1a2b3c forms, with variations for alpha channels and optional hash. Explained token by token.

```
/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
```

CSS hex colors come in a 3-digit shorthand (#fff) and the full 6-digit form (#1a2b3c). This pattern accepts exactly those two, hash required. The alternation order doesn't matter here because the anchors force a full-string match — a 6-digit color can't half-match the 3-digit branch.

## Token by token

| Token | Meaning |
|---|---|
| `^#` | start of string, then the literal hash |
| `(?:` | non-capturing group for the two length alternatives |
| `[0-9a-fA-F]{3}` | shorthand: exactly 3 hex digits (#fff) |
| `\|[0-9a-fA-F]{6}` | or the full form: exactly 6 (#1a2b3c) |
| `)$` | close the group, end of string |

## Examples

- ✓ matches: `#fff`
- ✓ matches: `#1a2b3c`
- ✓ matches: `#00FF00`
- ✗ does not match: `fff`
- ✗ does not match: `#12345`
- ✗ does not match: `#ggg`

## Variations

- `^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$` — CSS Color 4: also accepts #rgba and #rrggbbaa alpha forms
- `^#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$` — hash optional — for inputs where users paste bare hex

## FAQ

### Why not just [0-9a-fA-F]{3,6}?

A range quantifier would also accept 4- and 5-digit strings like #1234, which aren't valid classic hex colors (4 digits is valid only as the #rgba alpha shorthand). The alternation pins the lengths to exactly 3 or 6.

### Does this validate that the color looks right?

It validates syntax only — #000000 and #010101 are both just valid strings to a regex. For contrast checking or palette work, parse the channels and do the math (or use a color tool).

## Related patterns

- [Regex for UUID Validation](https://www.devkult.com/regex/uuid.md)
- [Regex for URL Slug Validation](https://www.devkult.com/regex/slug.md)
- [Regex for Username Validation](https://www.devkult.com/regex/username.md)

Open the interactive page: https://www.devkult.com/regex/hex-color