Javascript Regexp从变量动态生成? [英] Javascript Regexp dynamic generation from variables?
问题描述
如何将两个正则表达式模式构造成一个?
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.
推荐答案
你必须使用 RegExp
:
You have to use RegExp
:
str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));
当我连接字符串时,所有斜杠都消失了。
When I'm concatenating strings, all slashes are gone.
如果你的模式中有反斜杠来逃避特殊的正则表达式字符,(如 \(
),你必须在字符串中使用两个反斜杠(因为 \
是字符串中的转义字符): new RegExp('\\(')
与 / \(/
。
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 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
这篇关于Javascript Regexp从变量动态生成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!