javascript - 查找两个字符串值中单词的常见出现次数

标签 javascript regex arrays

假设我有两个字符串,如下所示

var tester = "hello I have to ask you a doubt";
var case   = "hello better explain me the doubt";

这种情况下,两个字符串都包含常用词,例如 hellodoubt。所以假设我的默认字符串是 tester 并且我有一个变量 case 并且它包含可以是任何东西的一组单词。我确实想实现 testercase 中的常用词数。它应该以对象的形式给我一个结果。

结果

{"hello" : 1, "doubt" : 1};

我目前的实现如下

var tester = "hello I have to ask you a doubt";
function getMeRepeatedWordsDetails(case){
    var defaultWords = tester.split(" ");
    var testWords    = case.split(" "), result = {};
    for(var testWord in testWords){
        for(var defaultWord in defaultWords){
            if(defaultWord == testWord){
                result[testWord] = (!result[testWord]) ? 1 : (result[testWord] + 1);  
            }
        }
    }
    return result;
}

我怀疑有 Regex 可以使这个任务更容易,因为它可以找到模式匹配。但不确定这可以使用正则表达式来实现。我需要知道我是否遵循正确的路径来做同样的事情。

最佳答案

您可以使用第一个正则表达式作为分词器将 tester 字符串拆分为单词列表,然后使用这些单词构建与单词列表匹配的第二个正则表达式。例如:

var tester = "a string with a lot of words";

function getMeRepeatedWordsDetails ( sentence ) {
  sentence = sentence + " ";
  var regex = /[^\s]+/g;
  var regex2 = new RegExp ( "(" + tester.match ( regex ).join ( "|" ) + ")\\W", "g" );
  matches = sentence.match ( regex2 );
  var words = {};
  for ( var i = 0; i < matches.length; i++ ) {
    var match = matches [ i ].replace ( /\W/g, "" );
    var w = words [ match ];
    if ( ! w )
      words [ match ] = 1;
    else
      words [ match ]++;
  }   
  return words;
} 

console.log ( getMeRepeatedWordsDetails ( "another string with some words" ) );

分词器是一行:

var regex = /[^\s]+/g;

当你这样做时:

tester.match ( regex )

你得到包含在tester中的单词列表:

[ "a", "string", "with", "a", "lot", "of", "words" ]

使用这样的数组,我们构建了第二个匹配所有单词的正则表达式; regex2 具有以下形式:

/(a|string|with|a|lot|of|words)\W/g

添加 \W 以仅匹配整个单词,否则 a 元素将匹配任何以 a 开头的单词。将 regex2 应用于 sentence 的结果是另一个数组,其中仅包含 regex2 中包含的单词,即同时包含在testersentence。然后 for 循环只计算 matches 数组中的单词,将其转换为您请求的对象。

但要注意:

  • 你必须在 sentence 的末尾至少放一个空格,否则 regex2 中的 \W 与最后一个词不匹配: sentence = sentence + ""
  • 您必须从 \W 捕获的匹配项中删除一些可能的额外字符:match = matches [ i ].replace (/\W/g, "")

关于javascript - 查找两个字符串值中单词的常见出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22365397/

相关文章:

regex - Notepad++ Regex 查找包含单词且不包含单词的行

javascript - JavaScript 中的正则表达式

javascript - React Native 保存输入数据

JavaScript 和 HTML 自定义提示框

javascript - 按钮 onClick 方法在 react 应用程序中不起作用

regex - R:在第一个分隔符出现时快速拆分字符串

C# 正则表达式验证文件名

javascript - 我如何创建一个可重用的函数来为变量对象属性设置状态?

php - 遍历 while 数组并向项目添加更多属性 - PHP

javascript - 在添加对象之前如何检查对象是否已存在于数组中?