/ 猿问

# 计算JavaScript中正则表达式的匹配数

2019-10-30 11:15:40

numSpaces : function(text) {

return text.match(/\s/).length;

}

numSpaces : function(text) {

return (text.split(/\s/).length -1);

}

## 3 回答

// 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

>>> 'hi  there'.match(/\s/g).length;

2

>>> 'hi  there'.match(/\s+/g).length;

1

var re = /\s/g,

count = 0;

while (re.exec(text) !== null) {

++count;

}

return count;

function count(re, str) {

if (typeof re !== "string") {

return 0;

}

re = (re === '.') ? ('\\' + re) : re;

var cre = new RegExp(re, 'g');

return ((str || '').match(cre) || []).length;

}

if (typeof re !== "string") {

return 0;

}

re = (re === '.') ? ('\\' + re) : re;

function count(re: string, str: string): number {

if (typeof re !== 'string') {

return 0;

}

re = (re === '.') ? ('\\' + re) : re;

const cre = new RegExp(re, 'g');

return ((str || '').match(cre) || []).length;

}

• 3 回答
• 0 关注
• 428 浏览

0/150