I stored a RegExp object in a variable and used it for mapping an array of strings into an array of objects (parsed e-mail recipients), but it doesn't work, as if a RegExp object couldn't run its .exec()
method more than once.
However, if I use a regular expression literal instead of the stored object, it works as intended.
I cannot understand the reason behind this behavior. Is it expected, or could it be a bug?
The code:
const pattern = /^\s*(?<name>\w.*?)?\W+(?<address>[a-zA-Z\d._-]+@[a-zA-Z\d._-]+\.[a-zA-Z\d_-]+)\W*$/gi;
const input = "John Doe jdoe@acme.com; Ronald Roe <rroe@acme.com>";
const splitValues = input.split(/[\r\n,;]+/).map(s => s.trim()).filter(s => !!s);
const matchGroups1 = splitValues.map(s => pattern.exec(s));
console.log('Using pattern RegExp object:', JSON.stringify(matchGroups1, null, 2));
const matchGroups2 = splitValues.map(s => /^\s*(?<name>\w.*?)?\W+(?<address>[a-zA-Z\d._-]+@[a-zA-Z\d._-]+\.[a-zA-Z\d_-]+)\W*$/gi.exec(s));
console.log('Using literal regular expression:', JSON.stringify(matchGroups2, null, 2));
The output:
[LOG]: "Using pattern RegExp object:", "[
[
"John Doe jdoe@acme.com",
"John Doe",
"jdoe@acme.com"
],
null
]"
[LOG]: "Using literal regular expression:", "[
[
"John Doe jdoe@acme.com",
"John Doe",
"jdoe@acme.com"
],
[
"Ronald Roe <rroe@acme.com>",
"Ronald Roe",
"rroe@acme.com"
]
]"