【问题标题】:Javascript regular expression to match words and count the number of times each word has occuredJavascript正则表达式匹配单词并计算每个单词出现的次数
【发布时间】:2015-12-21 07:27:45
【问题描述】:

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

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

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

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

【问题讨论】:

  • 可能重复检查this
  • @AshokVishwakarma 不,这确实是一个不同的问题。这个问题是关于计算特定单词的出现次数。
  • 检查this :)

标签: javascript regex


【解决方案1】:

您可以使用 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)

【讨论】:

  • 不共享前缀的单词怎么办?
  • 我认为通过“word1”、“word2”等,OP 只是在使用示例;我怀疑真正的搜索是搜索“香蕉”、“苹果”、“橙子”、“葡萄柚”等。
【解决方案2】:

您可以使用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”标志时,将重复调用这样的函数。对函数的每次调用都将包含整个匹配的子字符串作为第一个参数,随后的参数将是正则表达式中带括号的组匹配。

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2016-03-17
    • 2010-11-15
    • 2012-01-06
    相关资源
    最近更新 更多