简体   繁体   中英

JS regex match, condition without capturing

I need to capture number after 'id-odes=' but only number without this phrase. I wrote something like this

"id-odes=50388635:id-odes=503813535:id-odes=50334635"
    .match(/(?:id-odes=)([0-9]*)/g);

but it returns

["id-odes=50388635", "id-odes=503813535", "id-odes=50334635"]

instead of

[50388635, 503813535, 50334635]

Please help and explain why my way doesn't work properly. Thanks

Instead of just outputting the array, you can iterate over the results:

var re =/id-odes=([0-9]*)/g,
s = "id-odes=50388635:id-odes=503813535:id-odes=50334635";

while ((match = re.exec(s)) !== null) {
    console.log(match[1]);
}

Demo

If you want to iterate over the matches then you can use something like:

s = "id-odes=50388635:id-odes=503813535:id-odes=50334635"  
re = /(?:id-odes=)([0-9]*)/
while (match = re.exec(s))
{
    console.log(match[1]); // This is the number part
}

Assuming the whole string is in exactly this format you can of course use "id-odes=50388635:id-odes=503813535:id-odes=50334635".match(/[0-9]+/g) but that of course breaks if there are any other numbers in the string.

Explanation why .match(/(?:id-odes=)([0-9]*)/g); gives you the wrong result is quite simple: You get back everything that the regex matched, regardless of capturing groups.

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