简体   繁体   English

如何搜索字符串以查看其是否包含所有子字符串?

[英]How can search a string to see if it contains all substrings?

I will be using coffeescript/javascript/jquery and I need to return true if a string contains all of my substrings. 我将使用coffeescript / javascript / jquery,如果字符串包含我的所有子字符串,我需要返回true。

So, lets say that I have an array of substrings 'my', 'dog', 'spot'. 因此,可以说我有一个子字符串数组“ my”,“ dog”,“ spot”。 I need to return a true if my string is 'growing up my pet dog was named spot'. 如果我的绳子“长大了,我的爱犬被命名为Spot”,我需要返回一个true。 But I would need to return false if the string was 'I had a dog named spot'. 但如果字符串是“我有一只名叫spot的狗”,我将需要返回false。

I am thinking there is a way to do this with a regular expression, but can't seem to figure it out? 我认为有一种方法可以使用正则表达式来执行此操作,但似乎无法弄清楚?

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;
});

If you want to reuse the function in various parts of your application, give it a name, and provide the string to be searched as the second argument, which makes it the this value. 如果要在应用程序的各个部分中重用该函数,请给它命名,并提供要搜索的字符串作为第二个参数,这使其成为this值。

function hasWordInString(word) {
    return this.indexOf(word) !== -1;
}

var res = words.every(hasWordInString, mystring);

The other nice thing about .every() is that it short-circuits if false is returned, so the search stops once a non-matching word is found, making it a little more efficient. .every()的另一个.every()是,如果返回false ,它会短路,因此一旦找到不匹配的单词,搜索就会停止,从而使搜索效率更高。


Force whole word matching 强制整个单词匹配

If you want to ensure that the matched string is a whole word to avoid "dog" matching "dogma" for example, you will need to make use of RegExp word boundaries: 如果要确保匹配的字符串是一个完整的单词,例如避免“ dog”与“ dogma”匹配,则需要使用RegExp单词边界:

function hasWordInString(word) {
    return this.match(new RegExp("\\b"+word+"\\b"))!=null;
}
var res = words.every(hasWordInString,mystring);

An alternate method for the books: 书籍的替代方法:

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

Using the .every method with regex to assert word boundaries: 在正则表达式中使用.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

Right, if the array of substrings isn't a given: 是的,如果子字符串数组不是给定的:

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));

Then, to match any substring: 然后,匹配任何子字符串:

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

I got the char escaping regex I'm using to escape strings I'm passing to the RegExp constructor from here . 我得到了用于转义字符串的正则表达式正则表达式,我将从此处将其传递给RegExp构造函数。

You don't need regular expression for this - just use indexOf, check for each words, and return if any of the words was not found 您不需要为此使用正则表达式-只需使用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;
}
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));

http://jsfiddle.net/cgYTZ/ http://jsfiddle.net/cgYTZ/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查字符串是否包含所有子字符串的最快方法 - Fastest way to check if string contains all substrings Javascript - 如何检查一个字符串是否包含多个子字符串 - Javascript - How to check if a string contains multiple substrings Javascript:搜索数组以查看是否包含字符串的一部分 - Javascript: Search array to see if it contains part of string 如何用其他字符串 javascript 替换所有子字符串 - How to replace all substrings with other string javascript 如何替换字符串中由 {} 括起来的所有子字符串? - How to replace all substrings enclosed by {} in a string? 检查点击目标是否包含多个子字符串 - Check to see if the target of a click contains several substrings 查看字符串是否在子字符串数组中包含任何元素的最佳方法? 如果匹配则更换 - Best way to see if a string contains any elements in an array of substrings? And then replace if matched 给定一个字符串,如何生成所有可能的子字符串数组,其中每个子字符串最多包含N个字符,但不少于M个字符? - Given a string, how to generate all possible arrays of substrings where each substring contains no more than N, but not less than M chars? Javascript - 如何在一个条件下检查字符串是否包含多个子字符串 - Javascript - How to check if a string contains multiple substrings in one condition 如何检查字符串是否包含 JavaScript 中子字符串数组中的文本? - How to check if a string contains text from an array of substrings in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM