Regular Expressions Part 1
30 May 2022
2 min read
Regular expressions are a broad and complex topic. Most programmers usually shy away from even attempting to master them. Granted, the topic can look and seem daunting, but it's an essential topic nonetheless.
An introduction to Regular Expressions
What is a Regular Expression
We'll take a deep dive into the test() and exec() methods and see how to utilize them to match strings
We'll look at matching multiple occurrences of a pattern as well as single occurrences
We'll explore the different flags available to us e.g g flag
We'll look at how to use Character Sets and Ranges
How to use Quantifiers
How to Capture Groups
Build an Email validation system using regex.
So what are regular expressions? Let's have a look at a few definitions:
A regular expression is a specific kind of text pattern that you can use with many modern applications and programming languages. -Regular Expressions Cookbook, Second Edition
A regular expression is a sequence of characters that specifies a search pattern in text. Usually, such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. -Wikipedia
Regular expressions are patterns used to match character combinations in strings. -MDN
Pay close attention to the definitions, and you will recognize that a few words keep popping up:
So with that in mind, we can make a few assumptions :
Regular Expressions are patterns
Regular Expressions contain characters or strings of characters
You can use regular expressions to match, search or replace characters or strings of characters
Method One: Using Regular Expression Literal
let regex = /hello/;
In the first method, you create a pattern by passing in the literal pattern between the two slashes.
let regex = new RegExp('hello');
When using the second method, you use the in-built RegExp constructor function to create the pattern that will match. The function takes in the literal pattern that will match, as an argument.
So far, we've covered what a regular expression is, and how to create it. The next logical step is to look at how to use them. How do you test whether a sentence or a word matches the pattern specified in the regex? That is what I'll be covering in my next blog post. Thanks for taking the time to read this and happy coding!!
Family 👪 Code 👨🏿💻 Dogs 🐶See other articles by Ian