繁体   English   中英

Javascript正则表达式匹配单词并计算每个单词出现的次数

[英]Javascript regular expression to match words and count the number of times each word has occured

我有一个正则表达式来检查文件中的多个单词。

/((word1?)|(word2?)|(word3?)|(word4?)|(word5 ?)|(word6?)|(word7?))/gmi

有没有办法可以计算同一行f代码中每个单词的匹配数?

也就是说,当执行代码时,我希望每个单词都被计算在内。 (例如:word1:10匹配,单词2,11匹配...)

你可以使用replace()做这样的事情

 var string = 'word1 word3 word1 word2 word4 word5 word1 word1 word3 word2'; var count = {}; string.replace(/\\bword\\d+\\b/gmi, function($i) { count[$i] = count[$i] ? count[$i] + 1 : 1; }); console.log(count) 

更新:如果您想要所有字数,请使用

 var string = 'word1 word3 word1 word2 word4 word5 word1 word1 word3 word2'; var count = {}; string.replace(/\\b\\w+\\b/gmi, function($i) { count[$i] = count[$i] ? count[$i] + 1 : 1; }); console.log(count) 

或者,如果您只需要某个单词的字数,那么请使用

 var string = 'word1 word3 word1 word2 word4 word5 word1 word1 word3 word2'; var count = {}; string.replace(/\\b(word1|word2|word3|word4|word5|word6|word7)\\b/gmi, function($i) { count[$i] = count[$i] ? count[$i] + 1 : 1; }); console.log(count) 

您可以使用String.prototype.replace()函数。 它不会是一行代码,但它会非常简单:

var regex = /((word1?)|(word2?)|(word3?)|(word4?)|(word5 ?)|(word6?)|(word7?))/gmi;

var counts = {};
var sourceText = yourSourceTextWithWordsInIt;

sourceText.replace(regex, function(_, matched) {
  matched = matched.toLowerCase();
  counts[matched] = (counts[matched] || 1) + 1;
});

然后counts对象将包含您描述的内容。 String原型上的.replace()函数可以将函数作为其第二个参数。 当模式具有“g”标志时,将重复调用这样的函数。 对函数的每次调用都将包括整个匹配子字符串的第一个参数,后续参数将是来自正则表达式的带括号的组匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM