是否可以在javascript中组合正则表达式.
例如:
var lower = /[a-z]/;
var upper = /[A-Z]/;
var alpha = upper|lower;//Is this possible?
Run Code Online (Sandbox Code Playgroud)
即.我可以将正则表达式分配给变量,并使用模式匹配字符组合这些变量,就像在正则表达式中一样
Bry*_*y6n 48
答案是肯定的!您必须在RegExp类下初始化变量:
var lower = new RegExp(/--RegexCode--/);
var upper = new RegExp(/--RegexCode--/);
Run Code Online (Sandbox Code Playgroud)
因此,可以动态创建正则表达式.创建后:
"sampleString".replace(/--whatever it should do--/);
Run Code Online (Sandbox Code Playgroud)
然后你可以正常组合它们,是的.
var finalRe = new RegExp(lower.source + "|" + upper.source);
Run Code Online (Sandbox Code Playgroud)
geo*_*org 25
如果事先不知道regexp,
var one = /[a-z]/;
var two = /[A-Z]/;
var one_or_two = new RegExp("(" + one.source + ")|(" + two.source + ")")
Run Code Online (Sandbox Code Playgroud)
如果这只是你需要做一两次的事情,我会坚持按照其他答案的建议逐个进行.
但是,如果您需要做很多事情,那么一些辅助函数可能会提高可读性.例如:
var lower = /[a-z]/,
upper = /[A-Z]/,
digit = /[0-9]/;
// All of these are equivalent, and will evaluate to /(?:a-z)|(?:A-Z)|(?:0-9)/
var anum1 = RegExp.any(lower, upper, digit),
anum2 = lower.or(upper).or(digit),
anum3 = lower.or(upper, digit);
Run Code Online (Sandbox Code Playgroud)
如果你想使用这些功能,这里是代码:
RegExp.any = function() {
var components = [],
arg;
for (var i = 0; i < arguments.length; i++) {
arg = arguments[i];
if (arg instanceof RegExp) {
components = components.concat(arg._components || arg.source);
}
}
var combined = new RegExp("(?:" + components.join(")|(?:") + ")");
combined._components = components; // For chained calls to "or" method
return combined;
};
RegExp.prototype.or = function() {
var args = Array.prototype.slice.call(arguments);
return RegExp.any.apply(null, [this].concat(args));
};
Run Code Online (Sandbox Code Playgroud)
替代方案包含在非捕获组中,并与析取运算符结合使用,使其成为更复杂的正则表达式的一种更强大的方法.
请注意,在调用辅助函数之前,您需要包含此代码!
使用通用函数:
const getComposedRegex = (...regexes) => new RegExp(regexes.map(regex => regex.source).join("|"))
Run Code Online (Sandbox Code Playgroud)
然后用任意数量的正则表达式调用它。
const reg1 = /[w]{3}/i
const reg2 = /http/i
const composedReg = getComposedRegex(reg1, reg2)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
29545 次 |
最近记录: |