A regular expression with multiple words (in any order) without repetition

I am trying to search for sorting (using JavaScript) in a list of strings. Each line in the list has several words.

A search query may also contain multiple words, but the word order should not matter.

For example, in the line “This is a random line”, the query “trin and is” should match. However, these terms may not overlap. For example, “random random” as a query on the same line should not match.

I'm going to sort the results based on relevance, but I shouldn't have a problem with this, I just can't figure out how to create regular expressions. Any ideas?

+5
source share
4 answers

It is probably not a good idea to do this with a regular expression. The regular expression (pure, computer science) "cannot be counted." The only "memory" that he has at any moment is the state of DFA. To combine several words in any order without repetition, you need about 2 ^ n states. Perhaps this is a really awful regex.

(In addition, I mention the regular expressions "pure, computer science" because most implementations are actually extensions and allow you to do things that are not regular. I don’t know any extensions, of course, not a single one in JavaScript, do this, what you want to make less painless with a single template.)

(Object, in JavaScript), . . , . , 0, - ( , ), .

+3

trin and is :

/trin.*(?:and.*is|is.*and)|and.*(?:trin.*is|is.*trin)|is.*(?:trin.*and|and.*trin)/

, .

+4

, , .

var query   = "trin and is",
    target  = "This is a random string",
    search  = { },
    matches = 0;

query.split( /\s+/ ).forEach(function( word ) {
    search[ word ] = true;
});

Object.keys( search ).forEach(function( word ) {
    matches += +new RegExp( word ).test( target );
});

// do something useful with "matches" for the query, should be "3"
alert( matches );

, matches . - , "" , . + ( true false) , , +1 +0.

+1

, , , :

function filterMatch(itemStr, keyword){
    var words = keyword.split(' '), i = 0, w, reg;
    for(; w = words[i++] ;){
        reg = new RegExp(w, 'ig');
        if (reg.test(itemStr) === false) return false;   // word not found
        itemStr = itemStr.replace(reg, '');              // remove matched word from original string
    }
    return true;
}

// test
filterMatch('This is a random string', 'trin and is');   // true
filterMatch('This is a random string', 'trin not is');   // false
0

All Articles