In the previous lesson, we introduced the regular expression, a programming tool used to match patterns in a string. It is built into many different programming languages, and JavaScript is one of them.
The previous lesson focused on how to match a pattern using the built-in methods match()
and matchAll()
, as well as different matching modes that can be activated by providing the right flag. In this lesson, we are going to cover different ways to describe a pattern using the regular expression.
Matching a set of characters
In a regular expression, you can use a square bracket to match a set of characters instead of just one. For example,
1let regex = /[01234][56789][abc]/g;
2
3let str1 = "18b"; // matched
4let str2 = "98b"; // null, because 9 is outside of [01234]
5let str3 = "18z"; // null, because z is outside of [abc]
6
7console.log(str1.match(regex));
8console.log(str2.match(regex));
9console.log(str3.match(regex));
1[ '18b' ]
2null
3null
This regular expression defines the following pattern:
A number between0
and4
, followed by a number between5
and9
, followed by a letter betweena
andc
.
As a result, the str1
falls into this rage, but the other two don't.
There is a easier way to define a range of characters by using a hyphen (-
).