Let a regular expression ignore the order of the search terms [duplicate]
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 exampl开发者_如何学运维e 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?
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.
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?
See this answer: Regular Expressions: Is there an AND operator?
精彩评论