user5526811
user5526811

Reputation:

Get last occurrence using RegEx

I have a huge string with this inside:

linha[0] = '12/2010    281R$          272.139,05                            ';
linha[0] = '13SL         1R$          226.185,81                            ';

Both lines are separate, and I need get the last occurrence from both. I'm using the following regex to match the first one:

/linha\[0]\s=\s'(.*)';/

I would like to get the second "linha..." too, but I don't know exactly how.

That's how i'm using this regex to get the first "linha...":

string.match(/linha\[0]\s=\s'(.*)';/);

output:

linha[0] = '12/2010    281R$          272.139,05                            ';

Also, i can't do extra work, i need get the second occurrence using only regex.

Upvotes: 1

Views: 80

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382092

If you want to get the last occurrence of your regex in a string (and assuming it exists), you can do

var str = hugeString.match(/linha\[0]\s=\s'([^']*)';/g).pop();

(yes, I changed .* to [^']* for a better efficiency, ignore that if you have quotes in your inner string)

Now, if you want to extract just the submatch, you can do

var regex = /linha\[0]\s=\s'([^']*)';/g,
    arr,
    str;
while (arr = regex.exec(hugeString)) str = arr[1];

Upvotes: 2

Related Questions