tags:

views:

56

answers:

3

I let my users enter a search term: "foo bar".

I would to convert the user query to a string that matches the words, but ignoring the order:

bla foo bla bar   = match
    ^^^     ^^^
bla bar bla foo   = match (order = reversed)
    ^^^     ^^^
bla bla bla foo   = no match (only one word)
            ^^^
bar bla bla bla   = no match (only one word)
^^^

Note: The example contains 2 words, but my users will go wild, and will enter more words.

If the order is not to be ignored, it is simple: replace a spaces by ".*" and I have a very good match.

But how can I let the regular expression ignore the order, and still match both (or more) words?

Do I need to generate a regex that will match possible combinations of order?

A: 

I recommend a mixed approach. Store the search terms, |-separated, in a variable $search. Then look for /(?:$search) ... (?:$search)/g where (?:$search) is repeated a number of times equal to the number of search terms.

If it matches, split it into terms, sort, and check for repeats. If there are none, it matches; if there are repeats, go on to the next one.

Which .NET language are you using? We may want to give sample code.

Charles
+1  A: 

When order doesn't matter, it's basically a series of separate searches, right? Can you simply perform 1 search for each word, and only return results where all searches succeed?

BlueMonkMN
That was plan B. Using a single regular expression required less refactoring, and I'm lazy today.
GvS