Regex for Hex Color Codes

Regex that matches CSS hex colors like #fff and #1a2b3c. Try valid and invalid values and learn how to extend it for alpha channels.

Part of the free Regex Tester. Runs in your browser — nothing is uploaded.

Regex for Hex Color Codes

CSS hex colors are a hash followed by 3 or 6 hexadecimal digits. The pattern uses a repeated group to allow both lengths and is case-insensitive in practice.

Worked example: Valid and invalid hex colors

Pattern /^#(?:[0-9a-fA-F]{3}){1,2}$/ — test strings

^#(?:[0-9a-fA-F]{3}){1,2}$

#fff
#1A2b3C
#12345
123456
#gggggg

Result for each line

✓ match     #fff
✓ match     #1A2b3C
✗ no match  #12345
✗ no match  123456
✗ no match  #gggggg

Practical tip

For 4- and 8-digit hex colors with an alpha channel, use ^#(?:[0-9a-f]{3,4}){1,2}$ with the i flag.

How to use this Regex Tester

  1. 1Use the live tool above — it runs entirely in your browser and never uploads your data.
  2. 2Paste the sample from the worked example, or use your own input.
  3. 3Copy the result, then adapt the same steps in your editor, script, or pipeline.

Regex for Hex Color Codes FAQs

How do I allow the alpha channel?

Allow 4 or 8 digits: ^#(?:[0-9a-f]{3,4}){1,2}$ with the i flag matches #rgb, #rgba, #rrggbb and #rrggbbaa.

Is the leading # required?

In CSS, yes. Make it optional with #? if your inputs may omit it, then normalize before use.

More Regex Tester pages

Open the full Regex Tester tool →