Javascript Regexp 从变量动态生成?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5090103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:36:57  来源:igfitidea点击:

Javascript Regexp dynamic generation from variables?

javascriptregexdynamic

提问by Somebody

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.

这不起作用。当我连接字符串时,所有斜线都消失了。

回答by Felix Kling

You have to use RegExp:

你必须使用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 twobackslashes in the string (because \is the escape character in a string): new RegExp('\\(')would be the same as /\(/.

如果您的模式中有一个反斜杠来转义特殊的正则表达式字符(如\(),则必须在字符串中使用两个反斜杠(因为\是字符串中的转义字符):new RegExp('\\(')将与/\(/.

So your patterns have to become:

所以你的模式必须变成:

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

回答by adarshr

Use the below:

使用以下:

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

str.match(regEx);

回答by 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);

回答by Vinoth Narayan

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

RegExp 构造函数创建一个正则表达式对象,用于将文本与模式匹配。

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

Above code works perfectly for me...

上面的代码非常适合我......