简体   繁体   English

JS正则表达式匹配,条件没有捕获

[英]JS regex match, condition without capturing

I need to capture number after 'id-odes=' but only number without this phrase. 我需要在'id-odes ='之后捕获数字,但只有没有这个短语的数字。 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. 假设整个字符串都是这种格式,你当然可以使用"id-odes=50388635:id-odes=503813535:id-odes=50334635".match(/[0-9]+/g)但当然如果字符串中有任何其他数字则中断。

Explanation why .match(/(?:id-odes=)([0-9]*)/g); 解释原因.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. 给你错误的结果非常简单:无论捕获组如何,你都可以获得正则表达式匹配的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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