在javascript中使用regex,如何在字符串中出现重复单词时检查条件? 单词可以位于字符串中的任何位置:
鉴于:“但男生跑得快,男生很强”或者 “男孩们”
预期结果:是的,因为“男孩”这个词有两个重复
答案 0 :(得分:3)
\b
匹配字边界
\w+
将匹配1个或多个单词字符
( ... )
为比赛创建了一个组
\1
将匹配匹配组#1的内容。
将它们组合在一起,您需要一个包含\b(\w+)\b.*\b\1\b
加上适当的反斜杠引用等。
@ guest27134指出上述不是完整的解决方案,因为OP需要true
/ false
,而不仅仅是正则表达式:
var result = a_string.match(/\b(\w+)\b.*\b\1\b/g) !== null
或者,甚至更短,如O.P。所建议的那样:
var result = /\b(\w+)\b.*\b\1\b/g.test(myStr)
答案 1 :(得分:0)
考虑到每个单词后面都有空格
var string = "but boys run fast boys are strong";
var strArray= string.split(" ");
var unique = [];
for(var i =0; i< strArray.length; i++)
{
eval(unique[strArray] = new Object());
}
答案 2 :(得分:0)
您可以计算每个匹配单词的出现次数
var str = "but boys run fast boys are strong";
var matches = str.split(/\s/);
var res = matches.map(function(match) {
return str.match(new RegExp(match, "g")).length;
});
var bool = res.some(function(len) {return len > 1}));
console.log(bool);
for (var i = 0; i < matches.length; i++) {
if (res[i] > 1) console.log(matches[i], i);
}
答案 3 :(得分:0)
如果你知道你正在测试重复的单词,可以使用像str.match(/boys/g).length > 1
这样的正则表达式来测试该单词是否出现多次(假设你的字符串在str
中变量)。
答案 4 :(得分:0)
你好,这是:
var temp = "but boys run fast boys are strong";
var count = (temp.match(/boys/g) || []).length;
console.log(count);
我希望我有所帮助!
答案 5 :(得分:0)
您好!
以下是您需要的确切答案的示例:
var keyword = "boys"
var temp = "but boys run fast boys are strong";
var regex = new RegExp(keyword, "g");
var count = (temp.match(regex) || []).length;
if (count > 0) {
console.log("true, since there are " + count + " repeats of the word '" + keyword + "'");
} else {
console.log("false, not found.");
}
我希望我有所帮助!