Regular Expressions, or Regex for short, are special text strings which are used to find and match patterns within text. Regex syntax is almost uniform across all programming languages, so once you learn the basics you can utilize it in any language (with some minor tweaks).
A Simple Problem
Imagine we needed to write some code which could determine whether a given string contained a 24 hour time in it. Something like:
"Let's meet at 11:45"
or
"I ran a 03:30 marathon"
How would we go about checking for the presence of a time in the string and extracting it? We could do it manually, using loops and a bunch of complex logic, but it's not that easy! It's not as simple for checking for a pattern of two numbers and then a colon and then two more numbers. We need to make sure the times are actually valid rather than any two digit numbers. What if we wanted to also allow the option to add in seconds?
"I ran a 03:30:19 marathon"
This could be really really frustrating to write, but fortunately we have Regular Expressions!
When are regular expressions useful?
Regular Expressions are commonly used for validating data, performing advanced searches, replacing/updating text, and a whole bunch more. Let's focus on validating user data for now. Regex are incredibly useful when you need to verify that information is formatted correctly. Here are a few of the extremely common formats we might need data to follow:
Trying to verify these patterns without the use of Regular Expressions is a nightmare 😭. It's possible, but it means writing tons of loops and complex logic.
Testing and Playing with Regular Expressions
<aside> 💡 I highly recommend using an online editor like https://regexr.com to test out your Regular Expressions. I'll be using it throughout this video.
</aside>