Javascript 查找两个字符串值中常见的单词
假设我有两个字符串,如下所示Javascript 查找两个字符串值中常见的单词,javascript,regex,arrays,Javascript,Regex,Arrays,假设我有两个字符串,如下所示 var tester = "hello I have to ask you a doubt"; var case = "hello better explain me the doubt"; var tester = "hello I have to ask you a doubt"; function getMeRepeatedWordsDetails(case){ var defaultWords = tester.split(" ");
var tester = "hello I have to ask you a doubt";
var case = "hello better explain me the doubt";
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;
}
这种情况下,两个字符串都包含常用词,如hello
和dis疑
。假设我的默认字符串是tester
,我有一个变量case
,它包含一组可以是任何东西的单词。我想实现tester
和case
中的常用词计数。它应该给我一个物体形式的结果
结果
{"hello" : 1, "doubt" : 1};
我当前的实现如下所示
var tester = "hello I have to ask you a doubt";
var case = "hello better explain me the doubt";
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;
}
正如我所怀疑的,有正则表达式可以使这项任务更容易,因为它可以找到模式匹配。但不确定使用正则表达式是否可以实现这一点。我需要知道我也在走正确的道路 您可以使用第一个正则表达式作为标记器,将
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" ) );
当您这样做时:
tester.match ( regex )
您将获得测试仪中包含的单词列表
:
[ "a", "string", "with", "a", "lot", "of", "words" ]
使用这样一个数组,我们构建了第二个正则表达式来匹配所有单词regex2
的形式如下:
/(a|string|with|a|lot|of|words)\W/g
添加\W
以仅匹配整个单词,否则a
元素将匹配以a
开头的任何单词。将regex2
应用于句子
的结果是另一个数组,其中只包含regex2
中包含的单词,即tester
和句子
中都包含的单词。然后for
循环只计算匹配的数组中的单词,将其转换为您请求的对象
但请注意:
- 您必须在
句子的末尾至少放一个空格,否则regex2
中的\W
与最后一个单词不匹配:句子=句子+”
- 您必须从已由
\W
捕获的匹配中删除一些可能的额外字符:match=matches[i]。替换(/\W/g,“”)
因此,如果“hello”
在测试仪中出现一次,在案例中出现两次,那么计数应该是1还是2?它应该是两次计数,如果在两个字符串中都出现两次呢?或者在测试仪中使用两次,在案例中使用一次,并且在标准阵列中使用的原因是?您还应该使用result.hasOwnProperty(testWord)
而不是!结果[testWord]
用于if语句。@字符串测试器将保持不变。测试器中重复出现的单词无关紧要。从tester中找到所有单词并找到出现的次数,以防stringI很高兴您的输入将其转换为VB.net,您应该在regex2-伟大解决方案的开头添加\b。