[英]JavaScript Regular Expression - Match Everything Except
I'm writing a JavaScript template parser, and I'm close to the final solution, however I want to allow whitespace in my template's binding blocks (which I'm matching with regular expressions). 我正在编写一个JavaScript模板解析器,我接近最终的解决方案,但是我想在模板的绑定块中允许空白(我与正则表达式匹配)。
Right now I have the following: 现在我有以下内容:
var codeblock = new RegExp("%\{[\S)]+\}%", 'g');
And given a template line that looks like: 并给出一个模板行,如下所示:
<td align="right" style="width: 123px;">%{toFixedEx(#{extendedPrice()}#,2,2)}%</td>
Will match: 将匹配:
%{toFixedEx(#{extendedPrice()}#,2,2)}%
However I want to allow whitespace and line breaks between the %{
and }%
, so I tried the following regexp: 但是我想在%{
和}%
之间允许空格和换行符,所以我尝试了以下正则表达式:
var codeblock = new RegExp("%\{[\S\s)]+\}%", 'g');
Which ends up matching: 最终匹配:
%{toFixedEx(#{surcharge()}#,2 ,4)}%</td>
<td align="right" style="width: 123px;">%{toFixedEx( #{extendedPrice()}#,2,2)}%
What I want to be able to do is match something like: 我想要做的是匹配以下内容:
%{
if (condition) {
toFixedEx(#{surcharge()}#,2 ,4)
}
else {
toFixedEx(0,2,4)
}
}%
Where the match ends at }%
instead of continuing on to the last closing brace in the template. 匹配结束于}%
而不是继续到模板中的最后一个右括号。 I tried subtraced character classes, however it does not look like they work in JavaScript. 我尝试过子跟踪的字符类,但它看起来不像是在JavaScript中工作。
var codeblock = new RegExp("%\{[\S\s]+?\}%", 'g');
+?
and *?
和*?
means: Match as less as possible to meet the condition of the next part of the RE. 意思是:尽可能少地匹配以满足RE下一部分的条件。
I have also removed the parenthesis, )
, from your RE, because [\\S\\s]
matches every character (including newlines). 我还从你的RE中删除了括号, )
因为[\\S\\s]
匹配每个字符(包括换行符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.