简体   繁体   中英

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM