1

Possible Duplicate:
Regular Expressions: Is there an AND operator?

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?

Community
  • 1
  • 1
GvS
  • 51,423
  • 16
  • 99
  • 138

3 Answers3

1

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
  • 10,775
  • 13
  • 64
  • 98
1

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
  • 24,307
  • 9
  • 78
  • 139
  • That was plan B. Using a single regular expression required less refactoring, and I'm lazy today. – GvS May 28 '10 at 14:09
0

See this answer: Regular Expressions: Is there an AND operator?

Community
  • 1
  • 1
Jacob Mattison
  • 48,909
  • 9
  • 107
  • 125