/^#?([a-f0-9]{6}|[a-f0-9]{3})$/
A Regular expression, or Regex, is a method of validating a specific piece of text by use of a sequence of characters each including their own fundimental principles. Regex can be used to validate emails, hex values, URLs, and HTML. In this case we will be focusing on Hex values which are typically a # with 6 numbers or letters following it.
- Anchors
- Quantifiers
- OR Operator
- Character Classes
- Flags
- Grouping and Capturing
- Bracket Expressions
- Greedy and Lazy Match
- Boundaries
- Back-references
- Look-ahead and Look-behind
In a Hex value the Regex it would look something like /^#?([a-f0-9]{6}|[a-f0-9]{3})$/
. To break it down:
[A-Fa-f0-9]{6}
- Will search for a hex value with letters between a-f, A-F and digits from 0-9 stretching 6 character spaces (ex: abc123)[A-Fa-f0-9]{3}
- Will search for a hex values with letters between a-f, A-F, and digits from 0-9 stretching only 3 character spaces (ex: a23)
The Anchors in a regex string are the ^
and $
, the ^
will represent the start of the string and the $
represents the end of the string
-^#?([a-f0-9]{6}|[a-f0-9]{3})$
everything in between the ^ and $ will be representing what the regex is looking for.
The Quantifiers will be the *
, ?
, and {}
. In this situation the ?
is showing that the #
will be followed by 0 or 1 characters
?([a-f0-9]{6}|[a-f0-9]{3})
The quantifier is saying after the # it will be either 0 or 1 characters
In this regex the |
is acting as the OR operator. The OR operator is there to tell the regex to look for either a {6} character hex value OR a {3} character hex value
[a-f0-9]{6}|[a-f0-9]{3}
the|
in the middle is representing that it will either be 6 characters or 3
Flags are for advanced searching with a regex, in the hex code value we can see that we have a multi-line flag by using a ^ and $ at the beginning and end of the string. This allows the expression to cross multi-lines of code without breaking it.
^#?([a-f0-9]{6}|[a-f0-9]{3})$
is showing that the hex value could be wrapped onto multiple lines
Grouping is shown by ()
around the regex, this allows us to seperate the meta characters from literal characters. Grouping can also be used to isolate part of a string or data in a program.
([a-f0-9]{6}|[a-f0-9]{3})
is showing only the literal values of the hex value and isn't specifying any meta search criteria.
The bracket expression are used to show which characters will be matched with the regex. In this expression we have the brackets showing we're looking for two strings including characters a-f and 0-9:
[a-f0-9]
My name is Dax Buratto and I am currently studying Full Stack Web Development at UT Austin. Check out my Github for more exciting stuff! Dax's Github