我将使用coffeescript / javascript / jquery,如果字符串包含我的所有子字符串,我需要返回true。
所以,让我说我有一系列子串'我','狗','现货'。如果我的字符串'成长,我的宠物狗被命名为现场',我需要返回一个真实的。但如果字符串是'我有一只叫做斑点的狗',我需要返回false。
我在想有一种方法可以用正则表达式做到这一点,但似乎无法弄明白?
答案 0 :(得分:6)
var mystring = "growing up my pet dog was named spot";
var words = ['my', 'dog', 'spot'];
var res = words.every(function(word) {
return mystring.indexOf(word) !== -1;
});
如果要在应用程序的各个部分重用该函数,请为其命名,并将要搜索的字符串作为第二个参数提供,这使其成为this
值。
function hasWordInString(word) {
return this.indexOf(word) !== -1;
}
var res = words.every(hasWordInString, mystring);
关于.every()
的另一个好处是,如果返回false
,它会短路,因此一旦找到不匹配的单词,搜索就会停止,从而使其效率更高。
强制全字匹配
如果你想确保匹配的字符串是一个完整的单词以避免“dog”匹配“dogma”,你将需要使用RegExp字边界:
function hasWordInString(word) {
return this.match(new RegExp("\\b"+word+"\\b"))!=null;
}
var res = words.every(hasWordInString,mystring);
答案 1 :(得分:1)
书籍的另一种方法:
var str1 = "growing up my pet dog was named spot";
var str2 = "I had a dog named spot";
var words = ['my','dog','spot'];
function str_match_array(str,array)
{
var found = array.filter(function(part) { return str.indexOf(part)>-1; });
//Or using regex and word boundaries:
var found = array.filter(function(part) { return str.match(new RegExp("\\b"+part+"\\b"))!=null; });
return (found.length == array.length);
}
str_match_array(str1,words);//true
str_match_array(str2,words);//false
使用带有正则表达式的.every
方法断言字边界:
function str_match_array(str,arr)
{
return arr.every(function(part) {
return str.match(new RegExp("\\b"+part+"\\b"))!=null;
});
}
var result = str_match_array(str1,words);//true
var result = str_match_array(str2,words);//false
答案 2 :(得分:1)
是的,如果子串数组不是给定的:
words = words.forEach(function(word)
{
return new RegExp(
word.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"),//escape
'i'//optional, to make matches case-insensitive
);
});
//for browsers that don't support forEach:
words = (function(words)
{//turn array of substrings into regex's
for (var i=0;i<words.length;i++)
{
words[i] = new RegExp(
words[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"),
'i'
);
}
return words;
}(words));
然后,匹配任何子字符串:
function checkAll(string, patterns)
{
patterns.forEach(function(pattern)
{//or for loop for older browsers...
if (!pattern.test(string))
{//no match found
return false;
}
}
return true;
}
checkAll('growing up my pet dog was named spot', words);//true
checkAll('growing up my pet DOG was named Spot', words);//true
checkAll('the quick brown fox jumps over the lazy dog', words);//false
我得到了用于转义字符串的字符串转义正则表达式我正在传递给RegExp
构造函数from here。
答案 3 :(得分:0)
你不需要正则表达式 - 只需使用indexOf,检查每个单词,如果找不到任何单词则返回
var check_string = function(string, words) {
var count = 0;
for (var i in words) {
if (string.indexOf(words[i]) === -1) {
return false;
}
}
return true;
}
答案 4 :(得分:0)
var ary=['my', 'dog', 'spot'];
var str="growing up my pet dog was named spot";
var temp="";
for(var i=0;i<ary.length;i++){
temp=temp+".*(?:"+ary[i]+").*";
}
var regex= new RegExp(temp);
alert(regex.test(str));