Qaynaq LABS · TOOLS

REGEX · JAVASCRIPT

Regex explained

^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

Matches a hexadecimal color code starting with '#' followed by either 3 or 6 hexadecimal digits (case-insensitive).

Token-by-token breakdown

TokenMeaningExample
^ Anchor: asserts position at start of the string #ABC
# Literal character '#' #
( Start of a non-capturing group (or alternation group) (
[ Start of a character class [
A-F Range of uppercase letters A to F A
a-f Range of lowercase letters a to f a
0-9 Range of digits 0 to 9 0
] End of character class ]
{6} Quantifier: exactly 6 occurrences of the preceding element (hex digits) 123456
| Alternation: matches either the preceding or following pattern |
[ Start of a character class [
A-F Range of uppercase letters A to F A
a-f Range of lowercase letters a to f a
0-9 Range of digits 0 to 9 0
] End of character class ]
{3} Quantifier: exactly 3 occurrences of the preceding element (hex digits) 123
) End of group )
$ Anchor: asserts position at end of the string 123

Matches

  • #abc
  • #ABC
  • #123
  • #123456
  • #a1b2c3
  • #FFFFFF
  • #000000
  • #fff

Does not match

  • #ab
  • #1234
  • #GHI
  • #12345
  • #1234567
  • abc
  • #123#
  • #123

Common pitfalls

  • Forgetting the '^' anchor may cause partial matches in longer strings.
  • Assuming the pattern matches 4 or 5 digit hex codes (it does not).
  • Overlooking case insensitivity in hex digits (e.g., '#aBc' is valid).
  • Not anchoring the end with '$' may allow trailing characters (e.g., '#123abc' would match if '$' is omitted).

Performance notes

The alternation between 6 and 3 digits is safe in JavaScript as it does not introduce catastrophic backtracking. However, anchoring both start ('^') and end ('$') is critical to prevent partial matches in longer strings.

About regular expressions

Regular expressions are tiny programs that match patterns in text. They're powerful and notoriously cryptic — most engineers can write them but few can read them confidently. Qaynaq Labs' regex explainer breaks any pattern into its constituent tokens, shows what each one does, and runs through both matching and non-matching examples so you can verify the logic.

Different regex flavors (JavaScript, PCRE, Python, Go) have subtle differences in syntax and supported features. Pick your flavor in the input — the explainer accounts for it.

Frequently asked

Does this pattern match 4 or 5 digit hex codes?

No, the pattern only matches 3 or 6 digit hex codes after the '#'.

Is the pattern case-sensitive?

No, the character class [A-Fa-f0-9] includes both uppercase and lowercase hex digits.

Can this pattern match color codes with alpha channels (e.g., #RRGGBBAA)?

No, this pattern only matches 3 or 6 digit hex codes without alpha channels.

Why use {6}|{3} instead of {3,6}?

Using {3,6} would match 4 or 5 digit codes, which are not valid hex color codes. The alternation ensures only 3 or 6 digits are matched.