簡體   English   中英

JS正則表達式匹配,條件沒有捕獲

[英]JS regex match, condition without capturing

我需要在'id-odes ='之后捕獲數字,但只有沒有這個短語的數字。 我寫了這樣的東西

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

但它回來了

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

代替

[50388635, 503813535, 50334635]

請幫助解釋為什么我的方式無法正常工作。 謝謝

您可以迭代結果,而不僅僅是輸出數組:

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

演示

如果你想迭代匹配,那么你可以使用類似的東西:

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
}

假設整個字符串都是這種格式,你當然可以使用"id-odes=50388635:id-odes=503813535:id-odes=50334635".match(/[0-9]+/g)但當然如果字符串中有任何其他數字則中斷。

解釋原因.match(/(?:id-odes=)([0-9]*)/g); 給你錯誤的結果非常簡單:無論捕獲組如何,你都可以獲得正則表達式匹配的所有內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM