Regular Expression in JavaScript – Explained with Examples
A regular expression (RegExp) is a JavaScript element used to bundle the patterns you wish to find in a specific string of characters such as text, password, and email address.
In other words, RegExp is effective for pattern-matching and search-and-replace operations on strings.
Syntax of JavaScript’s Regular Expression
/pattern/flags
As shown in the snippet above, a Regular Expression is composed of three main components:
- An opening and a closing slash (
/.../
) - A pattern enclosed between the pair of slashes
- Zero or more flags appended to the pair of slashes
Let’s see some examples.
Example 1: RegExp with Two Flags
/CodeSweetly/gi;
The regular expression in the snippet above consists of:
- The regular expression’s opening and closing slash (
/.../
) - The pattern we wish to find (
CodeSweetly
) - Two flags (
i
andg
).
The i
flag tells the computer to do a case-insensitive search of CodeSweetly
.
The g
flag instructs the system to search globally for the text that matches the CodeSweetly
pattern.
Therefore, JavaScript will not limit its search to the first string that matches CodeSweetly
. Instead, it will find all strings corresponding to the pattern’s sequence.
Example 2: RegExp Case-Insensitive Search
"I love CodeSweetly".search(/CodeSweetly/i);
We used the code above to do a case-insensitive search for the CodeSweetly
pattern in the "I love CodeSweetly"
string.
The snippet above consists of:
- The string value we wish to search (
"I love CodeSweetly"
) - A JavaScript
search()
method that we used to search the string for the regular expression pattern - The regular expression’s opening and closing slash (
/.../
) - The pattern we wish to find (
CodeSweetly
) - One flag (
i
).
Example 3: RegExp Pattern Replacement
const myText = "Walker walked into a shop while walking home.";const myReplacementResult = myText.replace(/walk/gi, "Jogg");
console.log(myReplacementResult);
// The invocation above will return:// "Jogger Jogged into a shop while Jogging home."
We used the code above to do a global case-insensitive replacement of the walk
pattern with the "Jogg"
string.
So, now that we know what a regular expression is, we can discuss the typical RegExp operators.
Regular Expression Operators
Below are the standard operators used with regular expressions.
- Groups and ranges
- Quantifiers
- Metacharacter
- Assertions
- Flags
Let’s discuss each operator.
Groups and Ranges
We use the groups and ranges operators to specify the groups and ranges of characters we wish to find in a specific string.
Types of groups and ranges RegExp operators
The common types of the groups and ranges operators are:
- Character set
- Not (also called caret)
- To
- Or
- Capturing Group
- Named Capturing Group
- Non-capturing group
Let’s discuss each “groups and ranges” RegExp operator.
Character set [abc]
A regular expression’s character set defines the set of characters you wish to find in a single character’s position.
Developers use a pair of square brackets ([...]
) to represent RegExp’s character set.
Below are some examples.
Example 1: Find only character g
in any single character position of a string
/[g]/;
The snippet above specifies the letter g
as a pattern we wish to find in any single character position of a string.
Therefore, we can use the RegExp above to match the first g
character in any single character position of a string like so:
"George grew greater than we imagined".match(/[g]/);
// The invocation above will return: ["g"]
You can also do a global match of all g
characters in any single character position of a string.
Here’s an example:
"George grew greater than we imagined".match(/[g]/g);
// The invocation above will return: ["g", "g", "g", "g"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"George grew greater than we imagined".match(/[g]/gi);
// The invocation above will return:// ["G", "g", "g", "g", "g"]
Example 2: Find characters g
, 6
, and e
in any single character position of a string
/[g6e]/;
The snippet above specifies characters g
, 6
, and e
as the pattern we wish to find in any single character position of a string.
Therefore, we can use the RegExp above to match the first g
, 6
, or e
character in any single character position of a string like so:
const string = "George grew 6 times greater than we imagined 6 years ago.";
string.match(/[g6e]/);
// The invocation above will return: ["e"]
You can also do a global match of all g
, 6
, and e
characters in any single character position of a string.
Here’s an example:
const string = "George grew 6 times greater than we imagined 6 years ago.";
string.match(/[g6e]/g);
// The invocation above will return:// ["e", "g", "e", "g", "e", "6", "e", "g", "e", "e", "e", "g", "e", "6", "e", "g"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
const string = "George grew 6 times greater than we imagined 6 years ago.";
string.match(/[g6e]/gi);
// The invocation above will return:// ["G", "e", "g", "e", "g", "e", "6", "e", "g", "e", "e", "e", "g", "e", "6", "e", "g"]
Example 3: Find the first h[aeiouy]p
pattern where the second character position can be a
, e
, i
, o
, u
, or y
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h[aeiouy]p/);
// The invocation above will return: ["hop"]
Example 4: Find h[aeiouy]p
globally wherein the second character position can be a
, e
, i
, o
, u
, or y
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h[aeiouy]p/g);
// The invocation above will return: ["hop", "hap", "hip"]
Example 5: Do a global case-insensitive match of h[aeiouy]p
wherein the second character position can be a
, e
, i
, o
, u
, or y
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h[aeiouy]p/gi);
// The invocation above will return: ["hop", "Hip", "hap", "hip", "HEP"]
NOT [^abc]
A regular expression’s NOT operator defines the set of characters you do not wish to find in a single character’s position.
RegExp’s NOT operator is defined by a caret symbol (^
) used as the first element of a character set ([^abc]
).
Below are some examples.
Example 1: Find a character that is NOT g
in any single character position of a string
/[^g]/;
The snippet above specifies the letter g
as a pattern we do not wish to find in any single character position of a string.
Therefore, we can use the RegExp above to match the first character that is not a lowercase letter g
in any single character position of a string like so:
"George grew greater than we imagined".match(/[^g]/);
// The invocation above will return: ["G"]
You can also do a global match of all non-lowercase letters g
in any single character position of a string.
Here’s an example:
"George grew greater than we imagined".match(/[^g]/g);
// The invocation above will return:// ["G", "e", "o", "r", "e", " ", "r", "e", "w", " ", "r", "e", "a", "t", "e", "r", " ", "t", "h", "a", "n", " ", "w", "e", " ", "i", "m", "a", "i", "n", "e", "d"]
Suppose you wish to do a case-insensitive global match of letters that are not g
. In such a case, add an i
flag like this:
"George grew greater than we imagined".match(/[^g]/gi);
// The invocation above will return:// ["e", "o", "r", "e", " ", "r", "e", "w", " ", "r", "e", "a", "t", "e", "r", " ", "t", "h", "a", "n", " ", "w", "e", " ", "i", "m", "a", "i", "n", "e", "d"]
Example 2: Find characters that are NOT g
, 6
, and e
in any single character position of a string
/[^g6e]/;
The snippet above specifies characters g
, 6
, and e
as the pattern we do not wish to find in any single character position of a string.
So, you can use it to match the first string character that is not lowercase letter g
, number 6
, or lowercase letter e
.
Here’s an example:
const string = "George grew 6 times greater than we imagined 6 years ago.";
string.match(/[^g6e]/);
// The invocation above will return: ["G"]
You can also do a global match of all characters that are not lowercase letters g
, number 6
, or lowercase letters e
in any single character position of a string.
Here’s an example:
const string = "George grew 6 times greater than we imagined 6 years ago.";
string.match(/[^g6e]/g);
// The invocation above will return:// ["G", "o", "r", " ", "r", "w", " ", " ", "t", "i", "m", "s", " ", "r", "a", "t", "r", " ", "t", "h", "a", "n", " ", "w", " ", "i", "m", "a", "i", "n", "d", " ", " ", "y", "a", "r", "s", " ", "a", "o", "."]
Suppose you wish to do a case-insensitive global match of letters that are not g
, 6
, and e
. In such a case, add an i
flag like this:
const string = "George grew 6 times greater than we imagined 6 years ago.";
string.match(/[^g6e]/gi);
// The invocation above will return:// ["o", "r", " ", "r", "w", " ", " ", "t", "i", "m", "s", " ", "r", "a", "t", "r", " ", "t", "h", "a", "n", " ", "w", " ", "i", "m", "a", "i", "n", "d", " ", " ", "y", "a", "r", "s", " ", "a", "o", "."]
Example 3: Find the first h[^iuy]p
pattern where the second character position is NOT i
, u
, or y
const string = "I hope to get a Hippy-hAppy hippopotamus named CHEPY.";
string.match(/h[^iuy]p/);
// The invocation above will return: ["hop"]
Example 4: Find h[^iuy]p
globally wherein the second character position is NOT i
, u
, or y
const string = "I hope to get a Hippy-hAppy hippopotamus named CHEPY.";
string.match(/h[^iuy]p/g);
// The invocation above will return: ["hop", "hAp"]
Example 5: Do a global case-insensitive match of h[^iuy]p
wherein the second character position is NOT i
, u
, or y
const string = "I hope to get a Hippy-hAppy hippopotamus named CHEPY.";
string.match(/h[^iuy]p/gi);
// The invocation above will return: ["hop", "hAp", "HEP"]
TO [a-z]
A regular expression’s TO operator defines the range of characters you wish to find in a single character’s position.
We use a hyphen (-
) between the two numbers or letters of a character set to represent RegExp’s TO operator.
Below are some examples.
Example 1: Find any of the letters a
TO e
(inclusive) in any single character position of a string
/[a-e]/;
The snippet above specifies the letters a
TO e
(inclusive) as a pattern we wish to find in any single character position of a string.
So, we can use the RegExp to match the first a
, b
, c
, d
, or e
character in any single character position of a string.
Here’s an example:
"GEORGE grew Greater than we IMAGINED".match(/[a-e]/);
// The invocation above will return: ["e"]
Note that the /[a-e]/
regular expression in the snippet above is the same as /[abcde]/
.
You can also do a global match of all a
TO e
characters in any single character position of a string.
Here’s an example:
"GEORGE grew Greater than we IMAGINED".match(/[a-e]/g);
// The invocation above will return: ["e", "e", "a", "e", "a", "e"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"GEORGE grew Greater than we IMAGINED".match(/[a-e]/gi);
// The invocation above will return:// ["E", "E", "e", "e", "a", "e", "a", "e", "A", "E", "D"]
Example 2: Find characters 5
TO 9
in any single character position of a string
/[5-9]/;
The snippet above specifies numbers 5
TO 9
(inclusive) as a pattern we wish to find in any single character position of a string.
So, you can use the RegExp to match the first 5
, 6
, 7
, 8
, or 9
characters in any single character position of a string.
Here’s an example:
const string = "George grew 278 times greater than we imagined in the year 1953.";
string.match(/[5-9]/);
// The invocation above will return: ["7"]
You can also do a global match of all 5
, 6
, 7
, 8
, and 9
characters in any single character position of a string.
Here’s an example:
const string = "George grew 278 times greater than we imagined in the year 1953.";
string.match(/[5-9]/g);
// The invocation above will return: ["7", "8", "9", "5"]
Example 3: Find the first h[a-y]p
pattern where the second character position can be any of the characters a
TO y
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h[a-y]p/);
// The invocation above will return: ["hop"]
Example 4: Find h[e-o]p
globally wherein the second character position can be any of characters e
TO o
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h[e-o]p/g);
// The invocation above will return: ["hop", "hip"]
Example 5: Do a global case-insensitive match of h[e-o]p
wherein the second character position can be any of characters e
TO o
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h[e-o]p/gi);
// The invocation above will return: ["hop", "Hip", "hip", "HEP"]
Example 6: Do a global match of h[1-5e-o]p
wherein the second character position can be numbers 1
TO 5
or letters e
TO o
const string = "I hope to get a Hippy-h4ppy h1ppopotamus named CH3PY.";
string.match(/h[1-5e-o]p/g);
// The invocation above will return: ["hop", "h4p", "h1p"]
OR x|y
A regular expression’s OR operator defines the two alternative patterns you wish to find in a string.
We use a vertical bar (|
) between the two alternative patterns we wish to find to represent RegExp’s OR operator.
Below are some examples.
Example 1: Find the letter a
OR e
in a given string
/[a|e]/;
The snippet above specifies the letter a
OR e
as the pattern we wish to find in a string.
Therefore, we can use the RegExp above to match the first letter a
or e
character in a given string like so:
"GEORGE grew Greater than we IMAGINED".match(/[a|e]/);
// The invocation above will return: ["e"]
You can also do a global match of all a
or e
characters.
Here’s an example:
"GEORGE grew Greater than we IMAGINED".match(/[a|e]/g);
// The invocation above will return: ["e", "e", "a", "e", "a", "e"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"GEORGE grew Greater than we IMAGINED".match(/[a|e]/gi);
// The invocation above will return:// ["E", "E", "e", "e", "a", "e", "a", "e", "A", "E"]
Example 2: Find character 5
OR r
in a given string
/[5|r]/;
The snippet above specifies the number 5
OR letter r
as a pattern we wish to find in a string.
Therefore, we can use the RegExp above to match the first number 5
or letter r
character in a given string like so:
const string = "George grew 578 times greater than we imagined in the year 1953.";
string.match(/[5|r]/);
// The invocation above will return: ["r"]
You can also do a global match of all number 5
or letter r
characters.
Here’s an example:
const string = "George grew 578 times greater than we imagined in the year 1953.";
string.match(/[5|r]/g);
// The invocation above will return: ["r", "r", "5", "r", "r", "r", "5"]
Example 3: Do a global case-insensitive match of pattern hippo
OR hippy
in a given string
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/hipp[o|y]/gi);
// The invocation above will return: ["Hippy", "hippo"]
Example 4: Do a global case-insensitive match of pattern chepy
OR get
in a given string
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/chepy|get/gi);
// The invocation above will return: ["get", "CHEPY"]
Capturing group (...)
A regular expression’s capturing group operator does the following:
- It groups zero or more patterns
- It captures (saves) each group
- The computer tags each group with a number backreference that you can use to recall the saved patterns
We use a pair of round brackets ((...)
) to represent the capturing group operator.
Below are some examples.
Group a pattern
/(Joy)/;
The snippet above used the capturing group operator to group the Joy
pattern.
Since (Joy
) is the first capturing group operator in the RegExp above, the computer will save the capture with a number 1
backreference.
Note that the pattern in the snippet above will match a "Joy"
string.
Here’s an example:
"Joy has a joyful friend named Joy".match(/(Joy)/gi);
// The invocation above will return: ["Joy", "joy", "Joy"]
Group two patterns
/(Joy)(Joy)/;
The snippet above used two capturing group operators to group two Joy
patterns.
The computer will save the first (Joy)
group with a number 1
backreference and the second with number 2
.
Note that the pattern in the snippet above will match a "JoyJoy"
string.
Here’s an example:
"Joyjoy has a joyful friend named Joyjoy".match(/(JoyJoy)/gi);
// The invocation above will return: ["Joyjoy", "Joyjoy"]
Group three patterns
/(Joy)(Joy)(Joy)/;
The snippet above used three capturing group operators to group three Joy
patterns.
The computer will save the first (Joy)
group with a number 1
backreference, the second with number 2
, and the third with number 3
.
Note that the pattern in the snippet above will match a "JoyJoyJoy"
string.
Here’s an example:
"Joyjoy has a joyful friend named Joyjoyjoyjoy".match(/(JoyJoyJoy)/gi);
// The invocation above will return: ["Joyjoyjoy"]
Recall a captured pattern within a regular expression
Once the computer has captured your RegExp pattern, you can use a backslash (\
) and the group’s backreference number to recall it.
Here’s an example:
/(Joy) has a \1ful friend named \1/;
The snippet above used a backslash and number 1
to recall the first capturing group.
Therefore, you can use the pattern to match a "Joy has a joyful friend named Joy"
string.
Here’s an example:
const string = 'My best friend Joy has a joyful friend named Joy';
string.match(/(Joy) has a \1ful friend named \1/i);
// The invocation above will return:[ 'Joy has a joyful friend named Joy', 'Joy', index: 15, input: 'My best friend Joy has a joyful friend named Joy', groups: undefined]
In the returned array above,
'Joy has a joyful friend named Joy'
refers to the matched pattern.'Joy'
indicates the matched capturing group pattern.index
refers to the index position where the matched pattern began.input
indicates the string on which you invokedmatch()
.groups
contains a collection of the named capturing groups you specified inmatch()
’s RegExp argument. Orundefined
if the regular expression does not contain any named capturing group.
Recall two captured patterns within a regular expression
Once the computer has captured your RegExp pattern, you can use a backslash (\
) and the group’s backreference number to recall it.
Here’s an example:
/(Pet)s make (Joy) \2ful when \1ting them/;
The snippet above used backslashes and backreferences to recall the first and second capturing groups.
Therefore, you can use the pattern to match a "Pets makes Joy joyful when petting them"
string.
Here’s an example:
const string = "My friend's pets make Joy joyful when petting them gently";
string.match(/(Pet)s make (Joy) \2ful when \1ting them/i);
// The invocation above will return:[ "pets make Joy joyful when petting them", "pet", "Joy", index: 12, input: "My friend's pets make Joy joyful when petting them gently", groups: undefined]
In the returned array above,
"pets make Joy joyful when petting them"
refers to the matched pattern."pet"
indicates the first matched capturing group pattern."Joy"
indicates the second matched capturing group pattern.index
refers to the index position where the matched pattern began.input
indicates the string on which you invokedmatch()
.groups
contains a collection of the named capturing groups you specified inmatch()
’s RegExp argument. Orundefined
if the regular expression does not contain any named capturing group.
Recall a regular expression’s captured patterns within a string
Once the computer has captured your RegExp pattern, you can use a dollar sign ($
) and the group’s backreference number to recall it within a replace()
method’s string argument.
Here’s an example:
const string = "Sofela Oluwatobi";const regExp = /(Sofela) (Oluwatobi)/;
string.replace(regExp, "My name is $2 $1.");
// The invocation above will return: "My name is Oluwatobi Sofela."
Named capturing group (?<name>)
The named capturing group operator defines the name of a capturing group.
In other words, a named capturing group helps you easily remember the name of your grouped patterns.
The named capturing group is defined by a ?<name>
syntax placed immediately after a capturing group’s opening parenthesis.
Below are some examples.
Example 1: Name one capturing group
const string = 'My best friend Joy has a joyful friend named Joy';
string.match(/(?<myBestFriend>Joy) has a \1ful friend named \1/i);
// The invocation above will return:[ 'Joy has a joyful friend named Joy', 'Joy', index: 15, input: 'My best friend Joy has a joyful friend named Joy', groups: {myBestFriend: 'Joy'}]
In the returned array above,
'Joy has a joyful friend named Joy'
refers to the matched pattern.'Joy'
indicates the matched capturing group pattern.index
refers to the index position where the matched pattern began.input
indicates the string on which you invokedmatch()
.groups
contains a collection of the named capturing groups you specified inmatch()
’s RegExp argument. Orundefined
if the regular expression does not contain any named capturing group.
Example 2: Name two capturing groups
const string = "My friend's pets make Joy joyful when petting them gently";
const result = string.match( /(?<petGroup>Pet)s make (?<joyGroup>Joy) \2ful when \1ting them/i);
result.groups.joyGroup; // 'Joy'result.groups.petGroup; // 'pet'
Non-capturing group (?:)
A regular expression’s non-capturing group operator allows you to group a pattern without capturing (saving) it.
In other words, the non-capturing group operator negates the capturing group’s default behavior of adding the grouped pattern to the returned array.
The non-capturing group is defined by a ?:
syntax placed immediately after a capturing group’s opening parenthesis.
Below are some examples.
Example 1: How to group a pattern without capturing it
const string = 'My best friend Joy has a joyful friend named Joy';
string.match(/(?:Joy) has a joyful friend named Joy/i);
// The invocation above will return:[ 'Joy has a joyful friend named Joy', index: 15, input: 'My best friend Joy has a joyful friend named Joy', groups: undefined]
You can see that the snippet above did not include the grouped pattern (Joy
) in the returned array. Instead, it added only the matched string.
Example 2: How to group a pattern without capturing it
const string = "My friend's pets make Joy joyful when petting them gently";
string.match(/(?:Pet)s make (Joy) joyful when petting them/i);
// The invocation above will return:[ 'pets make Joy joyful when petting them', 'Joy', index: 12, input: 'My friend's pets make Joy joyful when petting them gently', groups: undefined]
Notice that the snippet above did not include the first grouped pattern (Pet
) in the returned array.
However, the second grouped pattern (Joy
) and the matched string got included in the returned array.
The second grouped pattern (Joy
) got captured because we did not specify it as a non-capturing group.
Let’s now learn about the quantifiers RegExp operators.
Quantifiers
Regular expression’s quantifiers operators specify the quantity of characters or expressions you wish to find in a specific string.
Types of RegExp quantifier operators
The common types of quantifiers are:
- At least one
- Zero or One
- Zero or More
- Repeat (also called quantity specifier)
Let’s discuss each of the quantifier operators.
At least one +
Regular expression’s at least one operator specifies that you wish to find at least one consecutive occurrence of its preceding item.
We use a plus sign (+
) to represent the “at least one” operator.
Below are some examples.
Example 1: Find the consecutive occurrence of at least one letter g
/g+/;
The snippet above tells the computer to find at least one consecutive occurrence of the letter g
.
So, you can use the RegExp to match the first consecutive occurrence of at least one character g
of a string.
Here’s an example:
"George grew greater than we imagined".match(/g+/);
// The invocation above will return: ["g"]
You can also do a global match of all consecutive occurrences of at least one letter g
of a string.
Here’s an example:
"George grew greater than we imagined".match(/g+/g);
// The invocation above will return: ["g", "g", "g", "g"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"George grew greater than we imagined".match(/g+/gi);
// The invocation above will return: ["G", "g", "g", "g", "g"]
Example 2: Find the consecutive occurrence of at least one number 7
/7+/;
The snippet above tells the computer to find at least one consecutive occurrence of the number 7
.
So, you can use the RegExp to match the first consecutive occurrence of at least one number 7
of a string.
Here’s an example:
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";
string.match(/7+/);
// The invocation above will return: ["77"]
You can also do a global match of all consecutive occurrences of at least one number 7
of a string.
Here’s an example:
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";
string.match(/7+/g);
// The invocation above will return: ["77", "777", "77777"]
Example 3: Find the consecutive occurrence of at least one letter e
positioned between letters w
and t
/we+t/;
The snippet above tells the computer to find at least one consecutive occurrence of the letter e
positioned between letters w
and t
.
Therefore, you can use the RegExp above to match the first consecutive occurrence of at least one letter e
between letters w
and t
of a string like so:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet TWEETS on your Wetproof device?";
string.match(/we+t/);
// The invocation above will return: ["weeeeet"]
You can also do a global match of all consecutive occurrences of at least one letter e
between letters w
and t
of a string.
Here’s an example:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet TWEETS on your Wetproof device?";
string.match(/we+t/g);
// The invocation above will return: ["weeeeet", "weet", "weet"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet TWEETS on your Wetproof device?";
string.match(/we+t/gi);
// The invocation above will return: ["weeeeet", "weet", "weet", "WEET", "Wet"]
Zero or one ?
Regular expression’s zero or one operator specifies that you wish to find zero or one occurrence of its preceding item.
We use a question mark (?
) to represent the “zero or one” operator.
Below are some examples.
Example 1: Find zero or one occurrence of letter g
/g?/;
The snippet above tells the computer to find zero or one occurrence of the letter g
.
Therefore, you can use the RegExp above to match the first zero or one occurrence of character g
of a string like so:
"George grew greater than we imagined".match(/g?/);
// The invocation above will return: [""]
You can also do a global match of all zero or one occurrence of the letter g
of a string.
Here’s an example:
"George grew greater than we imagined".match(/g?/g);
// The invocation above will return:// ["", "", "", "", "g", "", "", "g", "", "", "", "", "g", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "g", "", "", "", "", ""]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"George grew greater than we imagined".match(/g?/gi);
// The invocation above will return:// ["G", "", "", "", "g", "", "", "g", "", "", "", "", "g", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "g", "", "", "", "", ""]
Example 2: Find zero or one occurrence of the number 7
/7?/;
The snippet above tells the computer to find zero or one occurrence of the number 7
.
So, you can use the RegExp to match the first zero or one occurrence of a number 7
of a string.
Here’s an example:
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";
string.match(/7?/);
// The invocation above will return: [""]
You can also do a global match of all zero or one occurrence of number 7
of a string.
Here’s an example:
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";
string.match(/7?/g);
// The invocation above will return:// ["", "", "", "", "", "", "", "", "", "", "", "", "7", "7", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "7", "7", "7", "", "7", "7", "7", "7", "7", "", "", "", "", "", "", "", "", "", "", "", ""]
Example 3: Find zero or one occurrence of letter e
positioned between letters w
and t
/we?t/;
The snippet above tells the computer to find zero or one occurrence of the letter e
positioned between letters w
and t
.
Therefore, you can use the RegExp to match the first zero or one occurrence of letter e
between letters w
and t
of a string like so:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet TWEETS on your Wetproof device?";
string.match(/we?t/);
// The invocation above will return: null
You can also do a global match of all zero or one occurrence of letter e
between letters w
and t
of a string.
Here’s an example:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet TWEETS on your Wetproof device?";
string.match(/we?t/g);
// The invocation above will return: null
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet TWEETS on your Wetproof device?";
string.match(/we?t/gi);
// The invocation above will return: ["Wet"]
Zero or more *
Regular expression’s zero or more operator specifies that you wish to find zero or more occurrences of its preceding item.
We use an asterisk (*
) to represent the “zero or more” operator.
Below are some examples.
Example 1: Find zero or more occurrences of letter g
/g*/;
The snippet above tells the computer to find zero or more occurrences of the letter g
.
Therefore, you can use the RegExp above to match the first zero or more occurrence of character g
of a string like so:
"George grew greater than we imagined".match(/g*/);
// The invocation above will return: [""]
You can also do a global match of all zero or more occurrences of the letter g
of a string.
Here’s an example:
"George grew greater than we imagggggggined".match(/g*/g);
// The invocation above will return:// ["", "", "", "", "g", "", "", "g", "", "", "", "", "g", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "ggggggg", "", "", "", "", ""]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"George grew greater than we imagggggggined".match(/g*/gi);
// The invocation above will return:// ["G", "", "", "", "g", "", "", "g", "", "", "", "", "g", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "ggggggg", "", "", "", "", ""]
Example 2: Find zero or more occurrences of the number 7
/7*/;
The snippet above tells the computer to find zero or more occurrences of the number 7
.
So, you can use the RegExp to match the first zero or more occurrence of a number 7
of a string.
Here’s an example:
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";
string.match(/7*/);
// The invocation above will return: [""]
You can also do a global match of all zero or more occurrences of number 7
of a string.
Here’s an example:
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";
string.match(/7*/g);
// The invocation above will return:// ["", "", "", "", "", "", "", "", "", "", "", "", "77", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "777", "", "77777", "", "", "", "", "", "", "", "", "", "", "", ""]
Example 3: Find zero or more occurrences of letter e
positioned between letters w
and t
/we*t/;
The snippet above tells the computer to find zero or more occurrences of the letter e
positioned between letters w
and t
.
Therefore, you can use the RegExp above to match the first zero or more occurrence of letter e
between letters w
and t
of a string like so:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/we*t/);
// The invocation above will return: ["weeeeet"]
You can also do a global match of all zero or more occurrences of letter e
between letters w
and t
of a string.
Here’s an example:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/we*t/g);
// The invocation above will return: ["weeeeet", "weet", "weet"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/we*t/gi);
// The invocation above will return: ["weeeeet", "weet", "weet", "wT", "WEET", "Wet"]
Repeat {...}
Regular expression’s repeat operator specifies that you wish to find a repeated occurrence of the operator’s preceding item.
We use a pair of curly brackets ({...}
) to represent RegExp’s repeat operator.
Below are some examples.
Example 1: Find any letter g
that repeats four consecutive times
/g{4}/;
The snippet above tells the computer to find any letter g
that repeatedly occurs four consecutive times.
So, you can use the RegExp to match the first character g
that repeatedly occurs four consecutive times in a string.
Here’s an example:
"GGGGGGeorgge grew greater than we imagggggggggggined".match(/g{4}/);
// The invocation above will return: ["gggg"]
You can also do a global match of all letter g
s that repeatedly occur four consecutive times in a string.
Here’s an example:
"GGGGGGeorgge grew greater than we imagggggggggggined".match(/g{4}/g);
// The invocation above will return: ["gggg", "gggg"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"GGGGGGeorgge grew greater than we imagggggggggggined".match(/g{4}/gi);
// The invocation above will return: ["GGGG", "gggg", "gggg"]
Example 2: Find any number 7
that repeats two consecutive times
/7{2}/;
The snippet above tells the computer to find any number 7
that repeatedly occurs two consecutive times.
So, you can use the RegExp to match the first number 7
that repeatedly occurs two consecutive times in a string.
Here’s an example:
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";
string.match(/7{2}/);
// The invocation above will return: ["77"]
You can also do a global match of all number 7
s that repeatedly occur two consecutive times in a string.
Here’s an example:
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";
string.match(/7{2}/g);
// The invocation above will return: ["77", "77", "77", "77"]
Example 3: Find any letter e
that repeats two consecutive times and positioned between letters w
and t
/we{2}t/;
The snippet above tells the computer to find any letter e
that repeatedly occurs two consecutive times and is between letters w
and t
.
Therefore, you can use the RegExp above to match the first letter e
that repeatedly occurs two consecutive times and is between letters w
and t
.
Here’s an example:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/we{2}t/);
// The invocation above will return: ["weet"]
You can also do a global match of all letter e
s that repeatedly occurs two consecutive times and is between letters w
and t
.
Here’s an example:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/we{2}t/g);
// The invocation above will return: ["weet", "weet"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/we{2}t/gi);
// The invocation above will return: ["weet", "weet", "WEET"]
Example 4: Find any letter p
that repeats between two and four consecutive times globally
const string = "I hope to get a Hippppy-happpy hippopotamus named CHEPPPPPPPPPPPPPPPPPpY.";
string.match(/p{2,4}/g);
// The invocation above will return: ["pppp", "ppp", "pp"]
Example 5: Find any case insensitive letter p
that repeats between two and unlimited consecutive times globally
const string = "I hope to get a Hippppy-happpy hippopotamus named CHEPPPPPPPPPPPPPPPPPpY.";
string.match(/p{2,}/gi);
// The invocation above will return:// ["pppp", "ppp", "pp", "PPPPPPPPPPPPPPPPPp"]
Important stuff to know about RegExp quantifiers
Keep these two essential pieces of info in mind whenever you choose to use any of RegExp’s quantifier operators.
All quantifier operators are greedy
All RegExp quantifiers are greedy by default.
In other words, quantifiers will automatically find the longest part of the given string that matches the specified RegExp pattern.
For instance, consider the snippet below:
"Mississippitown".match(/M[a-z]*i/i);
// The invocation above will return: ["Mississippi"]
The snippet above returned "Mississippi"
because "Mississippi"
is the longest part of "Mississippitown"
that matched the specified RegExp pattern (/M[a-z]*i/i
).
Let’s see how to make a quantifier non-greedy.
Making a RegExp quantifier operator non-greedy
You can make a quantifier non-greedy (also called lazy) by adding a question mark (?
) after the quantifier operator.
By so doing, the question mark will make the quantifier a lazy operator.
Therefore, the quantifier will find the shortest part of the given string that matches the specified RegExp pattern.
Here’s an example:
"Mississippitown".match(/M[a-z]*?i/i);
// The invocation above will return: ["Mi"]
Note that the question mark in the snippet above is not the same as the zero or one RegExp operator.
We place the “zero or one” operator after the item we wish to find zero or one occurrence of.
However, we place the lazy operator after the quantifier operator we wish to make non-greedy.
Let’s now learn about the metacharacters RegExp operators.
Metacharacters
Regular expression’s metacharacters are operators used to specify the precise type of characters you wish to find in a specific string.
Types of RegExp metacharacter operators
The common types of RegExp metacharacter operators are:
- Escape
- Wildcard (also called dot or period)
Let’s discuss each RegExp metacharacter operator.
Escape \
Regular expression’s escape operator specifies that you wish to escape a character’s default type. Instead, you want the computer to analyze the character using its alternate meaning.
We use a backslash (\
) to represent RegExp’s escape operator.
Below are some examples.
Example 1: Escape +
’s default type
/\+/;
The snippet above tells the computer to escape +
’s default type (which by default means “at least one”). Instead, it should use +
literally as a plus sign.
So, you can use the RegExp to match the first plus sign of a string like this:
const string = "George grew 50 + 27 times greater than we imagined 1000 + 90+++ years ago.";
string.match(/\+/);
// The invocation above will return: ["+"]
You can also do a global match of all plus signs of a string.
Here’s an example:
const string = "George grew 50 + 27 times greater than we imagined 1000 + 90+++ years ago.";
string.match(/\+/g);
// The invocation above will return: ["+", "+", "+", "+", "+"]
Example 2: Escape d
’s default type
/\d/;
The snippet above tells the computer to escape d
’s default type (which by default means “lowercase letter d”). Instead, it should use d
as a special character to denote a digit (Hindu-Arabic numeral).
In other words, \d
is equivalent to [0-9]
(zero TO nine).
So, you can use the RegExp to match the first digit of a string like this:
const string = "George grew 50 + 27 times greater than we imagined 1000 + 90+++ years ago.";
string.match(/\d/);
// The invocation above will return: ["5"]
You can also do a global match of all digits.
Here’s an example:
const string = "George grew 50 + 27 times greater than we imagined 1000 + 90+++ years ago.";
string.match(/\d/g);
// The invocation above will return:// ["5", "0", "2", "7", "1", "0", "0", "0", "9", "0"]
Example 3: Escape D
’s default type
/\D/;
The snippet above tells the computer to escape D
’s default type (which by default means “uppercase letter D”). Instead, it should use D
as a special character to denote non-digit.
In other words, \D
is equivalent to [^0-9]
(NOT zero TO nine).
Therefore, you can use the RegExp above to match the first non-digit character of a string like so:
const string = "20 Plus 30 = 50.";
string.match(/\D/);
// The invocation above will return: [" "]
You can also do a global match of all non-digits characters.
Here’s an example:
const string = "20 Plus 30 = 50.";
string.match(/\D/g);
// The invocation above will return:// [" ", "P", "l", "u", "s", " ", " ", "=", " ", "."]
Example 4: Escape w
’s default type
/\w/;
The snippet above tells the computer to escape w
’s default type (which by default means “lowercase letter w”). Instead, it should use w
as a special character to denote a word (that is, the alphanumeric characters, including the underscore (_
) character).
In other words, \w
is equivalent to [A-Za-z0-9\_]
(uppercase A TO Z, lowercase a TO z, zero TO nine, and underscore).
Therefore, you can use the RegExp above to match the first word character of a string like so:
const string = "20 Plus 30 = 50.";
string.match(/\w/);
// The invocation above will return: ["2"]
You can also do a global match of all word characters.
Here’s an example:
const string = "20 Plus 30 = 50.";
string.match(/\w/g);
// The invocation above will return:// ["2", "0", "P", "l", "u", "s", "3", "0", "5", "0"]
Example 5: Escape W
’s default type
/\W/;
The snippet above tells the computer to escape W
’s default type (which by default means “uppercase letter W”). Instead, it should use W
as a special character to denote non-word.
In other words, \W
is equivalent to [^A-Za-z0-9\_]
(NOT uppercase A TO Z, lowercase a TO z, zero TO nine, nor underscore).
Therefore, you can use the RegExp above to match the first non-word character of a string like so:
const string = "20 Plus 30 = 50.";
string.match(/\W/);
// The invocation above will return: [" "]
You can also do a global match of all non-word characters.
Here’s an example:
const string = "20 Plus 30 = 50.";
string.match(/\W/g);
// The invocation above will return: [" ", " ", " ", "=", " ", "."]
Example 6: Escape s
’s default type
/\s/;
The snippet above tells the computer to escape s
’s default type (which by default means “lowercase letter s”). Instead, it should use s
as a special character to denote whitespace.
In other words, \s
is equivalent to [ \t\r\n\f\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
(that is, space, tab, carriage return, new line, form feed, vertical tab, and other Unicode whitespace characters).
Therefore, you can use the RegExp above to match the first whitespace character of a string like so:
const string = "20 Plus 30 = 50.";
string.match(/\s/);
// The invocation above will return: [" "]
You can also do a global match of all whitespace characters.
Here’s an example:
const string = "20 Plus 30 = 50.";
string.match(/\s/g);
// The invocation above will return: [" ", " ", " ", " "]
Example 7: Escape S
’s default type
/\S/;
The snippet above tells the computer to escape S
’s default type (which by default means “uppercase letter S”). Instead, it should use S
as a special character to denote non-whitespace.
In other words, \S
is equivalent to [^ \t\r\n\f\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
(that is, NOT space, tab, carriage return, new line, form feed, vertical tab, nor other Unicode whitespace characters).
So, you can use the RegExp to match the first non-whitespace character of a string like this:
const string = "20 Plus 30 = 50.";
string.match(/\S/);
// The invocation above will return: ["2"]
You can also do a global match of all non-whitespace characters.
Here’s an example:
const string = "20 Plus 30 = 50.";
string.match(/\S/g);
// The invocation above will return:// ["2", "0", "P", "l", "u", "s", "3", "0", "=", "5", "0", "."]
Example 8: Escape t
’s default type
/\t/;
The snippet above tells the computer to escape t
’s default type (which by default means “lowercase letter t”). Instead, it should use t
as a special character to denote the horizontal tab.
Therefore, you can use the RegExp above to match the first tab character of a string like so:
const string = "20 Plus 30 = 50.";
string.match(/\t/);
// The invocation above will return: ["\t"]
You can also do a global match of all tab characters.
Here’s an example:
const string = "20 Plus 30 = 50.";
string.match(/\t/g);
// The invocation above will return: ["\t", "\t", "\t", "\t"]
Example 9: Escape xf8
’s default type
/\xf8/;
The snippet above tells the computer to escape xf8
’s default type (which by default means “letters x, f, and number 8”). Instead, it should use xf8
as a special character to denote the two digits hexadecimal number f8—which represents the slashed zero character (ø
).
Therefore, you can use the RegExp above to match the first slashed zero character of a string like so:
const string = "20øs Plus 30øs = 50øs.";
string.match(/\xf8/);
// The invocation above will return: ["ø"]
You can also do a global match of all slashed zero characters.
Here’s an example:
const string = "20øs Plus 30øs = 50øs.";
string.match(/\xf8/g);
// The invocation above will return: ["ø", "ø", "ø"]
Example 10: Escape x3d
’s default type
/\x3d/;
The snippet above tells the computer to escape x3d
’s default type (which by default means “letter x, number 3, and letter d”). Instead, it should use x3d
as a special character to denote the two digits hexadecimal number 3d—which represents the equals character (=
).
Therefore, you can use the RegExp above to match the first equals character of a string like so:
const string = "20øs Plus 30øs === 50øs.";
string.match(/\x3d/);
// The invocation above will return: ["="]
You can also do a global match of all “equals” characters.
Here’s an example:
const string = "20øs Plus 30øs === 50øs.";
string.match(/\x3d/g);
// The invocation above will return: ["=", "=", "="]
Example 11: Escape u2195
’s default type
/\u2195/;
The snippet above tells the computer to escape u2195
’s default type (which by default means “letter u, and numbers 2, 1, 9 and 5”). Instead, it should use u2195
as a special character to denote the four digits Unicode hexadecimal number 2195—which represents the up-down arrow character (↕
).
Therefore, you can use the RegExp above to match the first up-down arrow character of a string like so:
const string = "20↕s Plus 30↕s = 50↕s.";
string.match(/\u2195/);
// The invocation above will return: ["↕"]
You can also do a global match of all up-down arrow characters.
Here’s an example:
const string = "20↕s Plus 30↕s = 50↕s.";
string.match(/\u2195/g);
// The invocation above will return: ["↕", "↕", "↕"]
Example 12: Escape u{24ED}
’s default type
/\u{24ED}/;
The snippet above tells the computer to escape u{24ED}
’s default type (which by default means “letter u, left curly bracket, numbers 2 and 4, letters E and D, and the right curly bracket”). Instead, it should use u{24ED}
as a special character to denote the four digits Unicode hexadecimal number 24ED—which represents the negative circled number thirteen character (⓭
).
Therefore, you can use the RegExp above to match the first negative circled number thirteen character of a string like so:
const string = "20⓭s Plus 30⓭s = 50⓭s.";
string.match(/\u{24ED}/u);
// The invocation above will return: ["⓭"]
You can also do a global match of all negative circled number thirteen characters.
Here’s an example:
const string = "20⓭s Plus 30⓭s = 50⓭s.";
string.match(/\u{24ED}/gu);
// The invocation above will return: ["⓭", "⓭", "⓭"]
Example 13: Escape u{23BD9}
’s default type
/\u{23BD9}/;
The snippet above tells the computer to escape u{23BD9}
’s default type (which by default means “letter u, left curly bracket, numbers 2 and 3, letters B and D, number 9, and the right curly bracket”). Instead, it should use u{23BD9}
as a special character to denote the five digits Unicode hexadecimal number 23BD9—which represents the CJK Unified Ideograph-23BD9 character (𣯙
).
So, you can use the RegExp to match the first CJK Unified Ideograph-23BD9 character of a string like this:
const string = "20𣯙s Plus 30𣯙s = 50𣯙s.";
string.match(/\u{23BD9}/u);
// The invocation above will return: ["𣯙"]
You can also do a global match of all CJK Unified Ideograph-23BD9 characters.
Here’s an example:
const string = "20𣯙s Plus 30𣯙s = 50𣯙s.";
string.match(/\u{23BD9}/gu);
// The invocation above will return: ["𣯙", "𣯙", "𣯙"]
Wildcard .
Regular expression’s wildcard operator specifies that you wish to find any character that is not the newline or any other line terminator characters.
We use a dot (.
) to represent RegExp’s wildcard operator.
Below are some examples.
Example 1: Find any character—except newlines and line terminators
/./;
The snippet above tells the computer to find any character except the newline and line terminator characters.
So, you can use the RegExp to match the first character that is not a newline or line terminator character:
const string = "20 Plus 30 = 50.";
string.match(/./);
// The invocation above will return: ["2"]
You can also do a global match of all characters that are not a newline or line terminator characters:
const string = "20 Plus 30 = 50.";
string.match(/./g);
// The invocation above will return:// ["2", "0", " ", "P", "l", "u", "s", " ", "3", "0", " ", "=", " ", "5", "0", "."]
Example 2: Find the first h.p
pattern where the second character position can be any character
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h.p/);
// The invocation above will return: ["hop"]
Example 3: Find h.p
globally wherein the second character position can be any character
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h.p/g);
// The invocation above will return: ["hop", "hap", "hip"]
Example 4: Do a global case-insensitive match of h.p
wherein the second character position can be any character
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/h.p/gi);
// The invocation above will return: ["hop", "Hip", "hap", "hip", "HEP"]
So, now that we know what metacharacters do, let’s learn about the assertion operators.
Assertions
Regular expression’s assertions operator asserts the precise location in a string where you wish to find a RegExp pattern.
Types of RegExp assertion operators
The common types of RegExp assertion operators are:
- Start of
- End of
- Word boundary
- Non-word boundary
- Positive lookahead
- Negative lookahead
- Positive lookbehind
- Negative lookbehind
Let’s discuss each of the assertion operators.
Start of ^
Regular expression’s start of operator asserts that you wish to find the RegExp pattern at the start of a string.
We use a caret symbol (^
) at the beginning of the pattern we wish to find at the beginning of a string to represent the “start of” operator.
Below are some examples.
Example 1: Find any character g
at the start of a string
/^g/;
The snippet above specifies the letter g
as a pattern we wish to find at the start of a string.
So, you can use the RegExp to match the first g
character at the beginning of a string.
Here’s an example:
"George grew greater than we imagined".match(/^g/);
// The invocation above will return: null
The snippet above returned null
because an uppercase letter G
began the string—not a lowercase letter g
.
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"George grew greater than we imagined".match(/^g/i);
// The invocation above will return: ["G"]
Note that the caret symbol in the snippet above is not the same as the NOT RegExp operator.
We use the NOT operator in a character set to define the set of characters we do not wish to find in a single character’s position.
However, we place the “start of” operator at the beginning of the pattern we wish to find at the start of a string.
Example 2: Find any pattern Geo
at the start of a string
const string = "George grew 6 times greater than we imagined 6 years ago.";
string.match(/^Geo/);
// The invocation above will return: ["Geo"]
End of $
Regular expression’s end of operator asserts that you wish to find the RegExp pattern at the end of a string.
We use a dollar sign ($
) at the end of the pattern we wish to find to represent RegExp’s “end of” operator.
Below are some examples.
Example 1: Find any character g
at the end of a string
/g$/;
The snippet above specifies the letter g
as a pattern we wish to find at the end of a string.
So, you can use the RegExp to match the first g
character at the end of a string.
Here’s an example:
"George grew greater than we imagined".match(/g$/);
// The invocation above will return: null
The snippet above returned null
because the letter d
ends the string—not the letter g
.
Example 2: Find any go
pattern at the end of a string
const string = "George grew 6 times greater than we imagined 6 years ago";
string.match(/go$/);
// The invocation above will return: ["go"]
Word boundary \b
Regular expression’s word boundary operator asserts that you wish to find the RegExp pattern at a word’s starting (or ending) boundary.
We use a backslash (\
) and the lowercase letter b
at the start (or end) of the pattern we wish to find to represent RegExp’s word boundary operator.
Below are some examples.
Example 1: Find any character g
at the start of a word
/\bg/;
The snippet above specifies the letter g
as a pattern we wish to find at the start of a word.
So, we can use the RegExp to match the first g
character at the start of a word.
Here’s an example:
"George grew greater than we imagined".match(/\bg/);
// The invocation above will return: ["g"]
You can also do a global match of all g
characters at the beginning of a word.
Here’s an example:
"George grew greater than we imagined".match(/\bg/g);
// The invocation above will return: ["g", "g"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"George grew greater than we imagined".match(/\bg/gi);
// The invocation above will return: ["G", "g", "g"]
Example 2: Find any character e
at the end of a word
/e\b/;
The snippet above specifies the letter e
as a pattern we wish to find at the end of a word.
So, we can use the RegExp to match the first e
character at the end of a word.
Here’s an example:
"George grew greater than we imagined".match(/e\b/);
// The invocation above will return: ["e"]
You can also do a global match of all e
characters at the end of a word.
Here’s an example:
"George grew greater than we imagined".match(/e\b/g);
// The invocation above will return: ["e", "e"]
Example 3: Do a global match of pattern gr
at the start of a word
const string = "George grew 6 times greater than we imagined 6 years ago";
string.match(/\bgr/g);
// The invocation above will return: ["gr", "gr"]
Example 4: Do a global case-insensitive match of pattern et
at the end of a word
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/et\b/gi);
// The invocation above will return: ["et"]
Non-word boundary \B
Regular expression’s non-word boundary operator asserts that you wish to find the RegExp pattern that is not at the starting (or ending) boundary of a word.
We use a backslash (\
) and uppercase letter B
at the start (or end) of the pattern we do not wish to find to represent RegExp’s non-word boundary operator.
Below are some examples.
Example 1: Find any character g
that is not at the start of a word
/\Bg/;
The snippet above specifies the letter g
as a pattern we do not wish to find at the start of a word.
Therefore, you can use the RegExp above to match the first g
character that is not at the start of a word like so:
"George grew greater than we imagined".match(/\Bg/);
// The invocation above will return: ["g"]
You can also do a global match of all g
characters that are not at the beginning of a word.
Here’s an example:
"George grew greater than we imagined".match(/\Bg/g);
// The invocation above will return: ["g", "g"]
Example 2: Find any character e
that is not at the end of a word
/e\B/;
The snippet above specifies the letter e
as a pattern we do not wish to find at the end of a word.
So, you can use the RegExp to match the first e
character that is not at the end of a word.
Here’s an example:
"George grew greater than we imagined".match(/e\B/);
// The invocation above will return: ["e"]
You can also do a global match of all e
characters that are not at the end of a word.
Here’s an example:
"George grew greater than we imagined".match(/e\B/g);
// The invocation above will return: ["e", "e", "e", "e", "e"]
Example 3: Do a global case-insensitive match of all et
patterns that are not at the end of a word
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/et\B/gi);
// The invocation above will return: ["et", "et", "ET", "et"]
Positive lookahead p(?=sp)
Regular expression’s positive lookahead operator asserts that you wish to find a RegExp pattern that is followed by another pattern.
Syntax
pattern(?=subpattern)
RegExp’s positive lookahead operator is defined by:
- A pattern
- An opening parenthesis
- A question mark
- An equals sign
- A subpattern
- A closing parenthesis
Below are some examples.
Example 1: Find any character g
that is followed by letter r
/g(?=r)/;
The snippet above specifies the letter g
as a pattern we wish to find if it is followed by the letter r
.
So, we can use the RegExp to match the first g
character that is followed by letter r
.
Here’s an example:
"George grew greater than we imagined".match(/g(?=r)/);
// The invocation above will return: ["g"]
You can also do a global match of all g
characters that are followed by the letter r
.
Here’s an example:
"George grew greater than we imagined".match(/g(?=r)/g);
// The invocation above will return: ["g", "g"]
Example 2: Do a global case-insensitive match of pattern ee
that is followed by letter t
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/ee(?=t)/gi);
// The invocation above will return: ["ee", "ee", "ee", "EE"]
Negative lookahead p(?!sp)
Regular expression’s negative lookahead operator asserts that you wish to find a RegExp pattern that is not followed by another pattern.
Syntax
pattern(?!subpattern)
RegExp’s negative lookahead operator is defined by:
- A pattern
- An opening parenthesis
- A question mark
- An exclamation mark
- A subpattern
- A closing parenthesis
Below are some examples.
Example 1: Find any character g
that is not followed by letter r
/g(?!r)/;
The snippet above specifies the letter g
as a pattern we wish to find if it is not followed by the letter r
.
So, we can use the RegExp to match the first g
character that is not followed by the letter r
.
Here’s an example:
"George grew greater than we imagined".match(/g(?!r)/);
// The invocation above will return: ["g"]
You can also do a global match of all g
characters that are not followed by the letter r
.
Here’s an example:
"George grew greater than we imagined".match(/g(?!r)/g);
// The invocation above will return: ["g", "g"]
Suppose you wish to do a case-insensitive match. In such a case, add an i
flag like this:
"George grew greater than we imagined".match(/g(?!r)/gi);
// The invocation above will return: ["G", "g", "g"]
Example 2: Do a global case-insensitive match of pattern ee
that is not followed by the letter t
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/ee(?!t)/gi);
// The invocation above will return: ["ee", "ee"]
Positive lookbehind (?<=sp)p
The positive lookbehind operator asserts that you wish to find a RegExp pattern that is preceded by another pattern.
Syntax
(?<=subpattern)pattern
RegExp’s positive lookbehind operator is defined by:
- An opening parenthesis
- A question mark
- A less-than symbol
- An equals sign
- A subpattern
- A closing parenthesis
- A pattern
Below are some examples.
Example 1: Find any character e
that is preceded by letter r
/(?<=r)e/;
The snippet above specifies the letter e
as a pattern we wish to find if it is preceded by the letter r
.
So, you can use the RegExp to match the first e
character that is preceded by the letter r
.
Here’s an example:
"George grew greater than we imagined".match(/(?<=r)e/);
// The invocation above will return: ["e"]
You can also do a global match of all e
characters that are preceded by the letter r
.
Here’s an example:
"George grew greater than we imagined".match(/(?<=r)e/g);
// The invocation above will return: ["e", "e"]
Example 2: Do a global case-insensitive match of pattern t
that is preceded by the letter ee
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/(?<=ee)t/gi);
// The invocation above will return: ["t", "t", "t", "T"]
Negative lookbehind (?<!sp)p
A regular expression’s negative lookbehind operator asserts that you wish to find a RegExp pattern that is not preceded by another pattern.
Syntax
(?<!subpattern)pattern
RegExp’s negative lookbehind operator is defined by:
- An opening parenthesis
- A question mark
- A less-than symbol
- An exclamation mark
- A subpattern
- A closing parenthesis
- A pattern
Below are some examples.
Example 1: Find any character e
that is not preceded by letter r
/(?<!r)e/;
The snippet above specifies the letter e
as a pattern we wish to find if it is not preceded by the letter r
.
So, we can use the RegExp to match the first e
character that is not preceded by the letter r
.
Here’s an example:
"George grew greater than we imagined".match(/(?<!r)e/);
// The invocation above will return: ["e"]
You can also do a global match of all e
characters that are not preceded by the letter r
.
Here’s an example:
"George grew greater than we imagined".match(/(?<!r)e/g);
// The invocation above will return: ["e", "e", "e", "e", "e"]
Example 2: Do a global case-insensitive match of pattern t
that is not preceded by the letter ee
const string = "Hellooo sweeeeetie! Have you checked CodeSweetly's supersweet ShowTime TWEETS on your Wetproof device?";
string.match(/(?<!ee)t/gi);
// The invocation above will return: ["T", "T", "t"]
Let’s now learn about the flag operators in RegExp.
Flags
Flags are operators used to specify how you want the computer to interpret a regular expression pattern.
Types of RegExp flags
The common types of RegExp flags are:
- Global
- Ignore case
- Multi-line
- Dot all
- Unicode
- Sticky
- Indices
Let’s discuss each of the flag operators.
Global g
Regular expression’s global flag tells the computer to do a global search for a RegExp pattern.
Therefore, the search will not stop after the first match. Instead, the system will find all matches.
We use the lowercase letter g
to represent RegExp’s global flag.
Below are some examples.
Example 1: Find character e
globally
/e/g;
The snippet above specifies the letter e
as a pattern we wish to find globally.
So, we can use the RegExp to do a global match of all e
characters in a string.
Here’s an example:
"George grew greater than we imagined".match(/e/g);
// The invocation above will return: ["e", "e", "e", "e", "e", "e", "e"]
Example 2: Find characters py
globally
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/py/g);
// The invocation above will return: ["py", "py"]
Ignore case i
The ignore case flag tells the computer to do a case-insensitive search for a RegExp pattern.
Therefore, the search will ignore checking whether the string is lowercase or uppercase. Instead, the system will match all cases.
We use a lowercase letter i
to represent RegExp’s ignore flag.
Below are some examples.
Example 1: Do a case-insensitive match of character g
/g/i;
The snippet above specifies the letter g
as a pattern we wish to find case-insensitively.
So, you can use the RegExp to do a case-insensitive match of the first g
character in a string like this:
"George grew greater than we imagined".match(/g/i);
// The invocation above will return: ["G"]
Example 2: Do a case-insensitive match of the first hip
character
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";
string.match(/hip/i);
// The invocation above will return: ["Hip"]
Multi-line m
Regular expression’s multi-line flag tells the computer to do a multiline search for a RegExp pattern.
Therefore, the search will search multiple lines for the specified pattern.
We use the lowercase letter m
to represent RegExp’s multi-line flag.
Below are some examples.
Example 1: Do a multi-line match of character g
/g/m;
The snippet above specifies the letter g
as a pattern we wish to find across multiple lines.
So, you can use the RegExp to do a multi-line match of the first g
character in a string.
Here’s an example:
"George grew \ngreater than we ima\ngined".match(/g/m);
// The invocation above will return: ["g"]
Example 2: Do a multi-line match of the first hip
character
const string = "I hope to get a \nHippy-happy \nhippopotamus named CHEPY.";
string.match(/hip/m);
// The invocation above will return: ["hip"]
Dot all s
Regular expression’s dot all flag tells the computer to allow a wildcard operator (.
) to match all characters—including a newline character.
We use the lowercase letter s
to represent RegExp’s “dot all” flag.
Below are some examples.
Example 1: Find any character—including newlines
/./s;
The snippet above tells the computer to find any character—including the newline character.
So, you can use the RegExp to find the first character in a string.
Here’s an example:
const string = "\n20 Plus 30 = 50.";
string.match(/./s);
// The invocation above will return: ["\n"]
Example 2: Find the first h.p
pattern where the second character position can be any character—including a newline
const string = "I h\npe to get a H\nppy-happy hippopotamus named CHEPY.";
string.match(/h.p/s);
// The invocation above will return: ["h\np"]
Unicode u
Regular expression’s Unicode flag tells the computer to search for Unicode RegExp patterns.
In other words, a Unicode flag indicates that a regular expression is a Unicode code point.
We use the lowercase letter u
to represent RegExp’s Unicode flag.
Below are some examples.
Example 1: Find the Unicode character \u{24ED}
/\u{24ED}/u;
The snippet above specifies the Unicode character \u{24ED}
as a pattern we wish to find in a string.
So, you can use the RegExp to match the first \u{24ED}
Unicode character of a string.
Here’s an example:
const string = "20⓭s Plus 30⓭s = 50⓭s.";
string.match(/\u{24ED}/u);
// The invocation above will return: ["⓭"]
Example 2: Find the Unicode character \u{23BD9}
const string = "20𣯙s Plus 30𣯙s = 50𣯙s.";
string.match(/\u{23BD9}/u);
// The invocation above will return: ["𣯙"]
Sticky y
Regular expression’s sticky flag tells the computer to find a RegExp pattern at exactly the lastIndex
position—not starting from the lastIndex
position.
In other words, the sticky flag specifies that you wish to stick to the lastIndex
position while searching for a RegExp pattern.
We use the lowercase letter y
to represent RegExp’s sticky flag.
Below are some examples.
Example 1: Execute a sticky search for character h
/h/y;
The snippet above specifies the letter h
as a pattern we wish to find at exactly the lastIndex
position.
So, you can use the RegExp to execute a search for character h
at exactly the lastIndex
position of a string.
Here’s an example:
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";const regExp = /h/y;
regExp.exec(string);
// The invocation above will return: null
The snippet above returned null
because regExp.lastIndex
is currently 0
. And the character at the string’s index 0
is I
—not h
.
In other words, the computer found no h
pattern at the lastIndex
position.
Keep in mind that you can specify the lastIndex
position you want the computer to stick to.
Here’s an example:
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";const regExp = /h/y;
regExp.lastIndex = 2;
regExp.exec(string);
// The invocation above will return: ["h"]
The snippet above searched for the letter h
at exactly the lastIndex
position (2
) only.
Example 2: Execute a sticky search for ew 7
at exactly the ninth index position
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";const regExp = /ew 7/y;
regExp.lastIndex = 9;
regExp.exec(string);
// The invocation above will return: ["ew 7"]
Indices d
Regular expression’s indices flag tells the computer to include each capturing group’s start and end indices in the result of the matched string.
We use the lower-case letter d
to represent RegExp’s indices flag.
Below are some examples.
Example 1: Get the indices of the e
pattern found in a string
/e/d;
The snippet above tells the computer to include the e
pattern’s start and end indices in the result of the matched string.
So, you can use the RegExp to get the start and end indices of the first e
pattern found in a string.
Here’s an example:
const string = "I hope to get a Hippy-happy hippopotamus named CHEPY.";const result = string.match(/e/d);
result.indices[0];
// The invocation above will return: [5, 6]
Example 2: Get the indices of the two capturing groups found in a string
const string = "George grew 77 times greater than we imagined 1777077777 years ago.";const result = string.match(/(77) (times)/d);
result.indices;
// The invocation above will return: [[12, 20], [12, 14], [15, 20]]
In the snippet above, note the following:
[12, 20]
contains the start and end indices of the two capturing groups—that is,(77)
and(times)
.[12, 14]
contains the start and end indices of the first capturing group—that is,(77)
.[15, 20]
contains the start and end indices of the second capturing group—that is,(times)
.
Useful Resources
Here are helpful tools you can use to debug your regular expressions: