忽略Javascript正则表达式模式中的空格? [英] Ignoring whitespace in Javascript regular expression patterns?
问题描述
根据我的研究,看起来Javascript的正则表达式没有任何内置等效于Perl的/ x修饰符或.NET的RegexOptions.IgnorePatternWhitespace修饰符。这些非常有用,因为它们可以使复杂的正则表达式更容易阅读。首先,我错过了什么,是否有一个内置的Javascript相当于这些?其次,如果没有,有没有人知道一个好的jQuery插件将实现这个功能?由于Javascript明显的正则表达式限制,将复杂的正则表达式压缩成一行是一种遗憾。
From my research it looks like Javascript's regular expressions don't have any built-in equivalent to Perl's /x modifier, or .NET's RegexOptions.IgnorePatternWhitespace modifier. These are very useful as they can make a complex regex much easier to read. Firstly, have I missed something and is there a Javascript built-in equivalent to these? Secondly, if there isn't, does anyone know of a good jQuery plugin that will implement this functionality? It's a shame to have to compress my complex regex into one line because of Javascript's apparent regex limitations.
推荐答案
如果我理解正确的话你想添加不属于正则表达式的空格吗?
据我所知,文字正则表达式是不可能的。
If I understand you correctly you want to add white space that isn't part of the regexp? As far as I know it isn't possible with literal regexp.
示例:
var a = /^[\d]+$/
您可以在以下几行中分解正则表达式:
You can break up the regexp in several lines like this:
var a = RegExp(
"^" +
"[\\d]+" + // This is a comment
"$"
);
请注意,由于它现在是普通字符串,因此必须使用\\转义\
Notice that since it is now a normal string, you have to escape \ with \\
或者如果你有一个复杂的:
Or if you have a complex one:
var digit_8 = "[0-9]{8}";
var alpha_4 = "[A-Za-z]{4}";
var a = RegExp(
digit_8 +
alpha_4 + // Optional comment
digit_8
);
更新:使用临时数组连接正则表达式:
Update: Using a temporary array to concatenate the regular expression:
var digit_8 = "[0-9]{8}";
var alpha_4 = "[A-Za-z]{4}";
var a = RegExp([
digit_8,
alpha_4, // Optional comment
digit_8,
"[0-9A-F]" // Another comment to a string
].join(""));
这篇关于忽略Javascript正则表达式模式中的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!