RegEx - LIFO buffer on match events

213 Views Asked by At

How is it possible to make a LIFO buffer on match events by using regex in Javascript?
Here's an example:

Input:

4   Mål Vålerenga, 1 - 0 Torgeir Børven. Målgivende pasning Daniel Fredheim Holm.<br> Dagens kaptein, Fredheim Holm, med en smart stikker til Børven, som drar seg fri og tupper ballen vakkert i lengste hjørne. Vålerenga innleder jubileet med 1-0!<br>
3    Fellah spilles fri på høyreflanken, men assistentdommeren vinker som om det skulle være 100-årsjubileum og 17. mai på en gang. Offside.
2   Corner Sarpsborg 08, Gudmundur Thórarinsson. Klareres.<br>
1    Kampen starter med forbrødring mellom keeperne. Kongshavn banker ballen helt over til kollega Sukke.<br>

Output should be:

1    Kampen starter med forbrødring mellom keeperne. Kongshavn banker ballen helt over til kollega Sukke.<br>
2   Corner Sarpsborg 08, Gudmundur Thórarinsson. Klareres.<br>
3    Fellah spilles fri på høyreflanken, men assistentdommeren vinker som om det skulle være 100-årsjubileum og 17. mai på en gang. Offside.<br>
4   Mål Vålerenga, 1 - 0 Torgeir Børven. Målgivende pasning Daniel Fredheim Holm.<br>
1

There are 1 best solutions below

0
On

It's not possible with regex alone (at least in JavaScript's regex flavor), but you can use regex matching or splitting and reverse:

If your input is as simple as in the question, then instead of matching you can split. We simply split the string at the beginning of each line:

result = str.split(/^/m).reverse().join("");

In more complex situations, splitting might not be that easy and you actually need to match. Still using your example, you could match the lines with .*\n (since . cannot match line breaks). In that case you can use

result = str.match(/.*\n/g).reverse().join("");

The problem here is to ensure that your matches will cover the entire input string - otherwise characters are lost in the process (this cannot happen with the split approach - but some problems will be to difficult to tackle with a JavaScript regex in split).