This is my example of a Regex Tutorial about how matching a Hex value works
This is a tutorial about a Regex. I will explain this line of code: Matching a Hex Value - /^#?([a-f0-9]{6}|[a-f0-9]{3})$/
- Anchors
- Quantifiers
- OR Operator
- Character Classes
- Flags
- Grouping and Capturing
- Bracket Expressions
- Greedy and Lazy Match
- Boundaries
- Back-references
- Look-ahead and Look-behind
We have the Regex, let us study: /^#?([a-f0-9]){6}|[a-f0-9]{3})$/
For this regex, the ^ is the start of the expression and the $ is the end of the expression.
the symbol # in this case refers to how hex codes show up within code.
There is usually a # before a hex code, such as #e65c00.
The ? is saying there may or may not be a # to indicate there is a hex code after the #. If there is, check for it. If not, still look for the rest of the regex values.
in this regex example, the Order operator is represented by ([a-f0-9]{6}|[a-f0-9]{3}), so, ([]{6}|[]{3}]). a(b|c) means search a, then for b followed by c. In my hex code regex, it says look for 6 characters first, and then, search for 3 characters.
[a-f] - any alphabetic letters between a through f. Lower case a, b, c, d, e, and or f. [0-9] - any digit or numeric number between 0 and 9. 0, 1, 2, 3, 4, 5, 6, 7, 8, and or 9. In any arrangemenet.
no flags in this expression
{6}|{3}
This is saying look for any text that contains 6 characters of letters between a - f, and or numbers between 0 - 9. Any arrangement of letters between those letters, and any arrangement of numbers.
OR look for 3 characters, either of letters between a - f, and or numbers between 0 - 9. Includes any arrangement of letters and numbers.
the section ([a-f0-9){6}|[a-f0-9{3}]);
the a-f is looking for any characters in the alphabet between a through f, so; a, b, c, d, e, and or f. The letters included in hex codes.
the 0-9 is looking for any digits between 0 and 9, so; 0, 1, 2, 3, 4, 5, 6, 7, 8, and or 9.
the {6} looks for 6 characters with either letters between a through f, or numbers between 0 and 9. For example, #ff0000 is a red. #ffffff is the color white. #0066ff is a rich sky blue color.
The boundaries in this regex are the 's, the ones before the ^ and after the
Tutorial by: Eiko Ujifusa
I found a lot of great info on this website here: https://regex101.com/r/iRxFEX/1 I used the w3 schools color picker for each beautiful hex code color example:
GitHub profile: https://github.com/eikouji
- used W3 school's color picker for screen caps. Try it here: https://www.w3schools.com/colors/colors_picker.asp
- used with https://regex101.com/ . Try it yourself! Just copy and paste /^#?([a-f0-9]{6}|[a-f0-9]{3})$/ and see what happens.