简体   繁体   中英

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).

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.

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.

I have also removed the parenthesis, ) , from your RE, because [\\S\\s] matches every character (including newlines).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM