最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

JavaScript Regex: Make ungreedy - Stack Overflow

matteradmin2PV0评论

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 %{}%?

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 %{}%?

Share Improve this question asked Feb 15, 2010 at 1:40 JamesBrownIsDeadJamesBrownIsDead 9352 gold badges9 silver badges15 bronze badges 1
  • As I always mention on Regular expression questions, check out Regexr, a cool Flash Based Regex tool, by gSkinner Link: gskinner./RegExr There is also the AS3 Regular Expression tester: idsklijnsma.nl/regexps – Moshe Commented Feb 15, 2010 at 1:49
Add a ment  | 

3 Answers 3

Reset to default 8

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 es from Matching newlines in JavaScript as a replacement for the DOTALL behaviour.

Shorter and faster working:

/%\{([^}]*)\}%/gm

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far