Reputation: 6824
Please check out this codepen for a working code example
I have two regular expressions
//Matches ol:whatever: and turns it into <ol>whatever</ol>
var olRegex = /ol:[\s\r\f\n]?([\s\S\r\f\n]*)[\r\f\n]:/;
//Matches li:whatever: and turns it into <li>whatever</li>
var liRegex = /li:(.*):/gi;
If I type
ol:
li:This is item 1:
li:This is item 2:
:
It will be correctly replaced by this output
<ol>
<li>This is item 1</li>
<li>This is item 2</li>
</ol>
But if I add 2 blocks like this
ol:
li:This is item 1:
li:This is item 2:
:
ol:
li:This is item 1:
li:This is item 2:
:
It does not produce what I expects, it produces this output instead
<ol>
<li>This is item 1</li>
<li>This is item 2</li>
: // I want the olRegex to stop matching here
ol:
<li>This is item 1</li>
<li>This is item 2</li>
</ol>
I want it to output
<ol>
<li>This is item 1</li>
<li>This is item 2</li>
</ol>
<ol>
<li>This is item 1</li>
<li>This is item 2</li>
</ol>
My olRegex
does not include the g
flag, why doesn't it stop matching when it encounters that first :
that stays on its own line?
Upvotes: 1
Views: 52
Reputation: 6075
In the line var olRegex = /ol:[\s\r\f\n]?([\s\S\r\f\n]*)[\r\f\n]:/;
the use of *
will read characters matching [\s\S\r\f\n]
as far as it until it finds the last possible [\r\f\n]:
(greedy).
Instead of *
you may use *?
which attempts to match those characters as few times as possible (lazy).
By doing this with the g
flag you will end up with the desired match groups.
Upvotes: 2