如果我清楚地理解,那么在這個例子match中找到所有長度為 0 的字串。空字串位于字串中所有符號的開頭、結尾和之間,因此有 11 個空字串
const str = '0123456789';
const regexp = /|/g;
const matches = str.match(regexp);
console.log('Length = ' matches.length);
console.log(matches);
在這個例子中,一切都很清楚。我只是搜索數字,所以有 10 位數字:
const str = '0123456789';
const regexp = /\d/g;
const matches = str.match(regexp);
console.log('Length = ' matches.length);
console.log(matches);
但我不明白為什么在嘗試組合 2 個正則運算式時我無法獲得 21 個匹配項:
const str = '0123456789';
const regexp1 = /|\d/g;
const matches1 = str.match(regexp1);
console.log('Length = ' matches1.length);
console.log(matches1);
const regexp2 = /\d|/g;
const matches2 = str.match(regexp2);
console.log('Length = ' matches2.length);
console.log(matches2);
uj5u.com熱心網友回復:
為什么在嘗試組合 2 個正則運算式時無法獲得 21 個匹配項?
因為.match()回傳非重疊匹配。它不會用多個匹配覆寫相同的字符(在每個位置),并且對于空匹配它不會回傳從相同索引開始的多個匹配。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496158.html
標籤:javascript 正则表达式
下一篇:在字串串列中搜索部分字串
