JavaScript Regex: Make ungreedy
I have this regex which looks for %{any charactering including new lines}%
:
/[%][{]\s*((.|\n|\r)*)\s*[}][%]/gm
If I test the regex on a string like "%{hey}%", the regex returns "hey" as a match.
However, if I give it "%{hey}%%{there}%", it doesn't match both开发者_如何学编程 "hey" and "there" seperately, it has one match—"hey}%%{there".
How do I make it ungreedy to so it returns a match for each %{}%?
Add a question mark after the star.
/[%][{]\s*((.|\n|\r)*?)\s*[}][%]/gm
Firstly, to make a wildcard match non-greedy, just append it with ?
(so *?
instead of *
and +?
instead of +
).
Secondly, your pattern can be simplified in a number of ways.
/%\{\s*([\s\S]*?)\s*\}%/gm
There's no need to put a single character in square brackets.
Lastly the expression in the middle you want to capture, you'll note I put [\s\S]
. That comes from Matching newlines in JavaScript as a replacement for the DOTALL
behaviour.
Shorter and faster working:
/%\{([^}]*)\}%/gm
精彩评论