Qaynaq LABS · TOOLS

REGEX · JAVASCRIPT

Regex explained

^[a-fA-F0-9]{6}$

Matches a string that is exactly 6 characters long, consisting only of hexadecimal digits (case-insensitive).

Token-by-token breakdown

TokenMeaningExample
^ Anchor: asserts position at start of the string Start of 'a1b2c3'
[ Start of a character class ...
a-f Range: matches any lowercase letter from 'a' to 'f' a, b, c, d, e, f
A-F Range: matches any uppercase letter from 'A' to 'F' A, B, C, D, E, F
0-9 Range: matches any digit from '0' to '9' 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
] End of the character class ...
{6} Quantifier: matches exactly 6 occurrences of the preceding element (the character class) 6 characters like 'a1b2c3'
$ Anchor: asserts position at end of the string End of 'a1b2c3'

Matches

  • a1b2c3
  • ABCDEF
  • 123456
  • deadbe
  • FEDCBA
  • 000000

Does not match

  • a1b2c
  • a1b2c34
  • ghijkl
  • a1b2c3!
  • a1b2c3
  • a1b2c3

Common pitfalls

  • Forgetting the anchors (^ and $) may allow strings longer than 6 characters to match partially.
  • Assuming the pattern matches any hexadecimal string without considering length constraints.
  • Overlooking case sensitivity if the pattern were written without both [a-fA-F] ranges.
  • Confusing hexadecimal with other alphanumeric patterns (e.g., base64).

Performance notes

This pattern is efficient with no risk of catastrophic backtracking. The character class is simple, and the quantifier is fixed. Anchors ensure exact length matching without unnecessary backtracking.

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 strings with leading or trailing whitespace?

No, because the anchors ^ and $ assert positions at the very start and end of the string, excluding any whitespace.

Can this pattern be used to validate hexadecimal color codes?

Yes, but only if the color code is exactly 6 characters long (e.g., '#a1b2c3' would not match; use a modified pattern like '^#?[a-fA-F0-9]{6}$' to allow an optional '#'.

Is the pattern case-sensitive?

No, because the character class includes both lowercase (a-f) and uppercase (A-F) ranges.