ChatGPT解决这个技术问题 Extra ChatGPT

Javascript Regexp dynamic generation from variables? [duplicate]

This question already has answers here: How do you use a variable in a regular expression? (23 answers) Closed 4 years ago.

How to construct two regex patterns into one?

For example I have one long pattern and one smaller, I need to put smaller one in front of long one.

var pattern1 = ':\(|:=\(|:-\(';
var pattern2 = ':\(|:=\(|:-\(|:\(|:=\(|:-\('
str.match('/'+pattern1+'|'+pattern2+'/gi');

This doesn't work. When I'm concatenating strings, all slashes are gone.


F
Felix Kling

You have to use RegExp:

str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));

When I'm concatenating strings, all slashes are gone.

If you have a backslash in your pattern to escape a special regex character, (like \(), you have to use two backslashes in the string (because \ is the escape character in a string): new RegExp('\\(') would be the same as /\(/.

So your patterns have to become:

var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';

a
adarshr

Use the below:

var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');

str.match(regEx);

Shouldn't the '/' be removed when using new RegExp(...)?
@BartKiers great point! Common mistake ! x) It would be worth adding a big notice somewhere :)
a
alex

You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.

var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);

V
Vinoth Narayan

The RegExp constructor creates a regular expression object for matching text with a pattern.

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
    str.match(regex);

Above code works perfectly for me...