簡體   English   中英

Js regexp 變量以獲取字符串中的所有匹配項

[英]Js regexp variable to get all matches in a string

有以下代碼:

s.match(/\+[A-Za-z0-9_]+/);

我用它從字符串中獲取所有 Jade mixin。 它適用於字符串中的一個 Jade mixin ("+article"),但不適用於 string("+article +b") 中的 2 個 mixins - 它僅返回包含第一項的數組。 我做錯了什么? 謝謝! 此外,如果沒有加號,則獲取帶有值的數組也會很好!

在正則表達式中添加全局標志g

s.match(/\+[A-Za-z0-9_]+/g);

更新:帶有刪除+符號的演示

 s = '+abc +4kk +ttt'; var res = s.match(/\\+[A-Za-z0-9_]+/g).map(function(v) { return v.substring(1) // get string after `+` }); document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

或帶有捕獲組的正則表達式

 var s = '+abc +4kk +ttt'; var reg = /\\+([A-Za-z0-9_]+)/g; var matches, res = []; while (matches = reg.exec(s)) { res.push(matches[1]); // get captured group value } document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

暫無
暫無

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

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