前提是:
- 你知道你在你的正则表达式中做了什么;
- 您有许多正则表达式片段来形成一个模式,它们将使用相同的标志;
- 您发现将小模式块分成一个数组更易读;
- 您还希望以后能够为下一个开发人员或您自己评论每个部分;
- 比起
new RegExp('this', 'g'),您更喜欢像/this/g 这样直观地简化您的正则表达式;
- 您可以在一个额外的步骤中组装正则表达式,而不是从一开始就将其组装成一个整体;
那么你可能喜欢这样写:
var regexParts =
[
/\b(\d+|null)\b/,// Some comments.
/\b(true|false)\b/,
/\b(new|getElementsBy(?:Tag|Class|)Name|arguments|getElementById|if|else|do|null|return|case|default|function|typeof|undefined|instanceof|this|document|window|while|for|switch|in|break|continue|length|var|(?:clear|set)(?:Timeout|Interval))(?=\W)/,
/(\$|jQuery)/,
/many more patterns/
],
regexString = regexParts.map(function(x){return x.source}).join('|'),
regexPattern = new RegExp(regexString, 'g');
然后您可以执行以下操作:
string.replace(regexPattern, function()
{
var m = arguments,
Class = '';
switch(true)
{
// Numbers and 'null'.
case (Boolean)(m[1]):
m = m[1];
Class = 'number';
break;
// True or False.
case (Boolean)(m[2]):
m = m[2];
Class = 'bool';
break;
// True or False.
case (Boolean)(m[3]):
m = m[3];
Class = 'keyword';
break;
// $ or 'jQuery'.
case (Boolean)(m[4]):
m = m[4];
Class = 'dollar';
break;
// More cases...
}
return '<span class="' + Class + '">' + m + '</span>';
})
在我的特定情况下(类似代码镜像的编辑器),执行一个大的正则表达式要容易得多,而不是像每次我用 html 标记替换以包装表达式时那样进行大量替换,在不影响 html 标记本身的情况下,下一个模式将更难定位(并且没有 javascript 不支持的良好 lookbehind):
.replace(/(\b\d+|null\b)/g, '<span class="number">$1</span>')
.replace(/(\btrue|false\b)/g, '<span class="bool">$1</span>')
.replace(/\b(new|getElementsBy(?:Tag|Class|)Name|arguments|getElementById|if|else|do|null|return|case|default|function|typeof|undefined|instanceof|this|document|window|while|for|switch|in|break|continue|var|(?:clear|set)(?:Timeout|Interval))(?=\W)/g, '<span class="keyword">$1</span>')
.replace(/\$/g, '<span class="dollar">$</span>')
.replace(/([\[\](){}.:;,+\-?=])/g, '<span class="ponctuation">$1</span>')