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
Anchors match a position from a string as opposed to a character.
^
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}
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.
|
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.
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.
Aspiring full-stack web developer with a focus on the front-end. Former student at The University of Texas at Austin.