Skip to content

Instantly share code, notes, and snippets.

@xaker00
Last active October 19, 2021 23:41
Show Gist options
  • Save xaker00/f78f5a45c1a16cbbad72bec86f4f6888 to your computer and use it in GitHub Desktop.
Save xaker00/f78f5a45c1a16cbbad72bec86f4f6888 to your computer and use it in GitHub Desktop.
Matching hex colors using regex

Identifying hex color using regex

HTML/CSS color are defined using six or three character hex values prefixed with an optional # symbol

/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i

Summary

This expression matches three or six valid hex digits prefixed with an optional #

Table of Contents

Regex Components

Anchors

A ^ symbol indicates start of string and a $ symbol marks the end.

Quantifiers

Three quantifiers are used in this expression.

  1. ? after the literal # indicates zero or one of #
  2. {6} requires six characters from the [a-f0f-9] class
  3. {3} requires six characters from the [a-f0f-9] class

Grouping Constructs

() characters designate a group. In this case the group is either 6 or 3 hex digits

Bracket Expressions

[a-f0f-9] matches characters a through f and 0 through 9

Character Classes

[a-f0f-9] matches characters a through f and 0 through 9

The OR Operator

The | symbol allows the hex string be either of the patterns

Flags

The i flag at the end makes the regex case insensitive

Character Escapes

Not used

Author

Ilya Spivakov (github link)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment