Javascript Regular Expressions create by RegExp constructor

Introduction

Regular expressions can be created by the RegExp constructor.

It accepts two arguments: a string pattern to match and an optional string of flags to apply.

Any regular expression that can be defined using literal syntax can be defined using the constructor.

Match the first instance of "bat" or "cat", regardless of case.

let pattern1 = /[bc]at/i; 
                      

Same as pattern1, just using the constructor.

let pattern2 = new RegExp("[bc]at", "i"); 

Here, pattern1 and pattern2 define equivalent regular expressions.

Both arguments of the RegExp constructor are strings.

Regular-expression literals should not be passed into the RegExp constructor.

Because the pattern argument of RegExp constructor is a string, we need to double-escape characters.

All meta characters must be double-escaped.

We also need to escape \n and so on.

The \ character, which is normally escaped in strings as \\ becomes \\\\ when used in a regular-expression string.

The following table shows some patterns in their literal form and the equivalent string that would be necessary to use the RegExp constructor.

LITERAL PATTERNSTRING EQUIVALENT
/\[bc\]at/ "\\[bc\\]at"
/\.at/ "\\.at"
/name\/age/"name\\/age"
/\d.\d{1,2}/ "\\d.\\d{1,2}"
/\w\\hello\\123/ "\\w\\\\hello\\\\123"

Creating a regular expression using a literal is not exactly the same as creating a regular expression using the RegExp constructor.

Regular-expression literals always share the same RegExp instance.

Creating a new RegExp via constructor always results in a new instance.

Consider the following:

let re = null;//from  ww  w .ja  v  a  2 s .c o  m
for (let i = 0; i < 10; i++) {
    re = /cat/g;
    re.test("category");
}
for (let i = 0; i < 10; i++) {
    re = new RegExp("cat", "g");
    re.test("category");
}

In the first loop, there is only one instance of RegExp created for /cat/, even though it is specified in the loop.

Instance properties of Regular-expression the are not reset.

Therefore calling test() fails every other time through the loop.

This happens because the "cat" is found in the first call to test().

The second call begins its search from index 3 (the end of the last match) and can't find it.

Because the end of the string is found, the subsequent call to test() starts at the beginning again.

The second loop uses the RegExp constructor to create the regular expression.

Each call to test() returns true because a new instance of RegExp is created for each iteration.

We can copy existing regular expression instances and optionally modify their flags using the constructor:

const re1 = /cat/g;/*from   www . ja v a 2  s. c o  m*/
console.log(re1); // "/cat/g" 

const re2 = new RegExp(re1);
console.log(re2); // "/cat/g" 

const re3 = new RegExp(re1, "i");
console.log(re3); // "/cat/i" 



PreviousNext

Related