This regular expression tutorial will focus on searching for hex values in a string.
This tutorial examines how to determine if a string is hexidecimal. The following regular expression is responsible for matching a hex:
RegEx Pattern
/^#?([a-f0-9]{6}|[a-f0-9]{3})$/
Below are some RegEx tests written in Javascript:
const regex = /^#?([a-f0-9]{6}|[a-f0-9]{3})$/;
console.log(regex.test('#fff')); // true
console.log(regex.test('#fff000')); // true
console.log(regex.test('#FFF000')); // false
console.log(regex.test('foobar')); // false
- Regular Expression Tutorial - Matching a Hex Value
- Summary
- Table of Contents
- Regex Components
- Anchors
- Quantifiers
- Flags
- Grouping and Capturing
- Greedy and Lazy Match
- Author
The pattern starts with the ^
anchor. This asserts the token following this is at the starting position of a string.
In the case of our regular expresion, we are asserting that the starting position matches the #
character literally (case sensitive).
At the end of our pattern, we have the $
quantifier, which asserts a token is at the ending position of a string. Given our regular expression, we are asserting that our string ends with one of the two possible capture groups (see Grouping and Capturing).
Following the ^#
characters, we have the ?
quantifier. This matches the previous token between zero and one times, as many times as possible greedy (see Greedy and Lazy Match).
That means we are looking for the #
character between zero and one times.
When looking at the pattern, you will notice two other quantifers:
{6}
and {3}
. These quantifiers specify that preceding token to {6}
matches exactly six times, and for {3}
, the preceding token matche exactly three times (see Grouping and Capturing for more details).
While our pattern does not include a flag, we could optionally append the i
modifier making our regular expression case-insensitive. Example below:
const regex = /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i;
console.log(regex.test('#fff000')); // true
console.log(regex.test('#FFF000')); // true
Immediately following the ^#?
sequence, we have what is called a capature group:
([a-f0-9]{6}|[a-f0-9]{3})
The capture group contains two alternatives:
[a-f0-9]{6}
and
[a-f0-9]{3}
The alternatives are separated by the |
common token. This token ensures the string matches either what is before the |
or what is after it.
The first alternative, [a-f0-9]{6}
, says that a single character must be preset in the list of characters [a-f0-9]
, and must match exactly six times.
The second alternative, [a-f0-9]{3}
, says that a single character must be present in the list of characters [a-f0-9]
, and must match exactly three times (refer to Quantifiers).
The ?
in our regular expression matches the preceding token between zero and one times, as many times as possible, as needed (greedy).
Alicia Jimenez
Future female coder. You can find her Github profile below: