Skip to content

Instantly share code, notes, and snippets.

@Johnhughes814
Last active April 29, 2022 04:55
Show Gist options
  • Save Johnhughes814/f607e8d593f6ac57d86df404afea7fab to your computer and use it in GitHub Desktop.
Save Johnhughes814/f607e8d593f6ac57d86df404afea7fab to your computer and use it in GitHub Desktop.
Hex code regex explained.

Regex Tutorial

Table of Contents

Introduction

In this tutorial I will be explaining how to use the following regex:

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

I will explain each of the components that this regex includes which will be broken down in the following way:

^ - Start anchor
( - Grouping
{3} -Quantifier
| -Or
[a-f0-9] -Bracket with characters
$ -Stop anchor
( -Grouping

This regex will search for a string that may or may not have a # at the front then either 6 or 3 characters with any combination of a-f and 0-9. The following are a few examples of string that would pass this regex.

#aa9
fe429b
#aaa943
001

Regex Components

Anchors

Anchors match a position from a string as opposed to a character.

^

Quantifiers

Quantifiers indicate that the preceding token must be matched a certain number of times. By default, quantifiers are greedy, and will match as many characters as possible.

*, +, ?, x{n}, x{n,}, x{n,m}

OR Operator

This regex is ivided by an OR operator |. In the group ([a-f0-9]{6}|[a-f0-9]{3}) we have two expresions: [a-f0-9]{6} and [a-f0-9]{3}. This means that our regex will sync up with any of those two expresions.

|

Character Classes + Bracket Expressions

These allow you to choose specific characters from a larget set to be accepted. In this example, we have two character sets, a-f and 0-9, which are inside another component used here, the bracket expressions.

Grouping and Capturing

Uses paranthese to enclose the string as what will be valid. Here only the entire regex is in one set of parentheses, so therefore there is one grouping.

Author

John Hughes

Aspiring full-stack web developer with a focus on the front-end. Former student at The University of Texas at Austin.

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