[英]How to match an overlapping pattern multiple times using RegExp
使用RegExp是否可以通過給定正則表達式/ aa / g(或類似名稱)來匹配兩倍於字符串“ aaa”的字符串? 假設第一個匹配是前兩個a,第二個匹配是最后兩個a。
像這樣:
您可以將reg
的lastIndex
更改為index+1
let str = "aaa", reg = /aa/g, next = reg.exec(str), res = []; while (next) { res.push(next[0]); reg.lastIndex = next.index + 1; next = reg.exec(str); } console.log(res);
您可以捕獲兩個的內先行,然后回去和匹配一個字符 。
let pattern = /(?=(a{2}))a/g; let resultMatches = []; let match; let stringToCheck = 'aaa'; while ((match = pattern.exec(stringToCheck)) !== null) resultMatches.push(match[1]); console.log(resultMatches);
使用'aaa'作為輸入返回['aa','aa'],而使用'aaaa'作為輸入將返回['aa','aa','aa']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.