Skip to content

Instantly share code, notes, and snippets.

Regex Tutorial: Matching a Hexidecimal Color Code

Regular expressions are patterns that can be matched against strings. They are denoted with / (a forward slash) at the beginning and the end of the pattern. To the average eye, a regular expression - or regex for short - might look like your cat walked across your computer's keyboard. It certainly left me baffled when I first saw one, but my love for patterns and logic prompted me to do some digging. After a little bit of research, I found that regular expressions can be decoded - admittedly, some more easily than others. But I realized that in the mess of characters I was looking at, there was a purpose to each piece. Let's break it down.

Summary

I could spend several days learning about different components found in regular expressions, but let's start with some basics. In this tutorial, I will break down the regular expression below, and explain how it will validate a Hexidecimal Color Code.

regex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/