Search This Blog

2023/04/25

Javascript:match vs matchAll

match():
match() is a method in JavaScript that returns an array of results matching a
string against a regular expression.Returned results depend a lot on using the
global(g) flag. If a g flag is used we will get all results but without
capturing groups.

Code:test1test2
const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/g;
const match = str.match(regex); //Array ["Exp", "Exr"]
console.log(match)

Output:
[ 'Exp', 'Exr' ]

On the other hand, if we don’t use the g flag we will get only the first
complete match but with related capturing groups.

Code:
const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/;
const match = str.match(regex); //Array ["Exp", "x", "p"]
console.log(match)
Output:
[
'Exp',
'x',
'p',
index: 7,
input: 'ReguralExpresion RegExr',
groups: undefined
]

matchAll():
matchAll() returns an iterator that returns all matched groups against a
regular expression, including capturing groups.

Code:
const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/g;
const match = str.matchAll(regex); //returns iterator
Array.from(match, (res) => console.log(res));

Output:
[
'Exp',
'x',
'p',
index: 7,
input: 'ReguralExpresion RegExr',
groups: undefined
]
[
'Exr',
'x',
'r',
index: 20,
input: 'ReguralExpresion RegExr',
groups: undefined
]

same code as above but with for-of loop;

Code:
const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/g;
const match = str.matchAll(regex); //returns iterator
for (const m of match) {
console.log(m);
}

Output:
[
'Exp',
'x',
'p',
index: 7,
input: 'ReguralExpresion RegExr',
groups: undefined
]
[
'Exr',
'x',
'r',
index: 20,
input: 'ReguralExpresion RegExr',
groups: undefined
]

One of the main reasons for using matchAll() over match() is the abilitiy to
access capture groups.

A regular expression for matchAll() needs to have a g flag, otherwise, an
error will be thrown.If there are no matches, match() method returns null but
if there is no match for matchAll() it will returns an empty iterable object.


What is each array element in output of matchall() stands for?

The iterator produces an array for each match, including the capturing groups
with a few extra properties like index, input and groups.Lets takes example of
first array element in above output.

Example:
[
'Exp',
'x',
'p',
index: 7,
input: 'ReguralExpresion RegExr',
groups: undefined
]

index: The index of the first result in the original string. In the above
example Exp starts at position 7 hence index has the value 7.
input: The complete string that matchAll() was run against. In the above
example, that was 'ReguralExpresion RegExr'.
groups: Contains the results of any named capturing groups specified in the
regular expression.

No comments:

Post a Comment