tl;dr: 通用模式计数器
// THIS IS WHAT YOU NEED
const count = (str) => {
const re = /YOUR_PATTERN_HERE/g
return ((str || '').match(re) || []).length
}
对于那些来到这里寻找一种通用方法来计算字符串中正则表达式模式的出现次数,并且不希望它在零出现的情况下失败的人来说,这个代码就是你需要的。下面是一个演示:
/*
* 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'`)
原始答案
初始代码的问题在于缺少全局标识符:
>>> 'hi there how are you'.match(/\s/g).length;
4
如果没有正则表达式的部分,它将仅匹配第一个匹配项并就此停止。g
另请注意,您的正则表达式将对连续的空格进行两次计数:
>>> 'hi there'.match(/\s/g).length;
2
如果这是不可取的,你可以这样做:
>>> 'hi there'.match(/\s+/g).length;
1