Is there a way to programmatically compare two regular expressions in Javascript and determine if they produce identical matches?
const regex1 = /[0-9]+/;
const regex2 = /\d+/;
const regex3 = /[A-Z]{2}/;
const regex4 = /[A-Z][A-Z]/;
isEquivalentRegExp(regex1, regex2); // true
isEquivalentRegExp(regex2, regex3); // false
isEquivalentRegExp(regex3, regex4); // true
I've tried using the source
attribute and the toString()
function to do that, but they don't work because they return the regular expression itself as a string.
// Not valid
function isEquivalentRegExp(r1, r2) {
return r1.toString() == r2.toString();
}
// Not valid
function isEquivalentRegExp(r1, r2) {
return r1.source == r2.source;
}