dmck
dmck

Reputation: 7861

Matching with [\S\s]*? vs (.)+ regexps

I am try to match the contents between two markers %{ and }% with JavaScript.

I have regular expressions that work in a regex tester, however when I put them into my code they do not work. I believe it may be an escaping issue, however I am not sure.

The following regex works, but does not allow whitespace:

var databinder = new RegExp("%\{(.)+\}%", 'g');

The following regex works in a regex tester, and allows white space, however it does not return any matchs in my code:

var databinder = new RegExp("%\{[\S\s]*?\}%", 'g');

It only works when I remove the:

[\S\s]*?

What is causing the regex to not work in the second example?

Here is an example of text I am matching:

<td align="right" style="width: 123px;">%{toFixedEx(#{surcharge()}#,2,4)}%</td>
<td align="right" style="width: 123px;">%{toFixedEx(#{extendedPrice()}#,2,2)}%</td>

Upvotes: 0

Views: 1171

Answers (1)

Digital Plane
Digital Plane

Reputation: 38264

You need to double escape the backslashes on any special regex modifiers when using a string:

var databinder = new RegExp("%\\{[\\S\\s]*\\}%", 'g');

or you can use a regex literal:

var databinder = /%\{[\S\s]*?\}%/g;

Upvotes: 5

Related Questions