3 回答

TA貢獻1803條經(jīng)驗 獲得超3個贊
通用模式計數(shù)器
// THIS IS WHAT YOU NEED
const count = (str) => {
const re = /YOUR_PATTERN_HERE/g
return ((str || '').match(re) || []).length
}
對于那些來到這里的人來說,他們正在尋找一種通用的方法來計算字符串中正則表達式模式的出現(xiàn)次數(shù),并且如果出現(xiàn)的次數(shù)為零,也不希望它失敗,那么此代碼就是您所需要的。這是一個示范:
/*
* Example
*/
const count = (str) => {
const re = /[a-z]{3}/g
return ((str || '').match(re) || []).length
}
const str1 = 'abc, def, ghi'
const str2 = 'ABC, DEF, GHI'
console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`)
console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)
原始答案
初始代碼的問題是缺少全局標(biāo)識符:
>>> 'hi there how are you'.match(/\s/g).length;
4
沒有g(shù)正則表達式的部分,它將僅匹配第一個匹配項并在此停止。
還要注意,您的正則表達式將對連續(xù)的空格計數(shù)兩次:
>>> 'hi there'.match(/\s/g).length;
2
如果不希望這樣做,則可以執(zhí)行以下操作:
>>> 'hi there'.match(/\s+/g).length;
1

TA貢獻1802條經(jīng)驗 獲得超10個贊
如我先前的回答中所述,您可以RegExp.exec()用來遍歷所有匹配并計算每次匹配;優(yōu)點僅限于內(nèi)存,因為總體而言,它比使用慢約20%String.match()。
var re = /\s/g,
count = 0;
while (re.exec(text) !== null) {
++count;
}
return count;
添加回答
舉報