Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match string in any word order regex

Tags:

regex

word

I am having to write few patterns which will be used for matching purpose through Regex upon user input:

string pattern = "^.*overview\ of\ sales.*customer\ information.*$";
string input = "overview of sales with customer information";

Is there a way(s) to remove the word order in Regex? So

string pattern = "^.*overview\ of\ sales.*customer\ information.*$";

will also match:

string input = "customer information with overview of sales";

This can probably be done by writing every pattern in reverse order but as number of patterns are quite few and will grow with time and number of *. This tends to be tedious way of doing it so please guide on this matter.

like image 458
kashif4u Avatar asked Nov 10 '13 22:11

kashif4u


1 Answers

You'll want to use positive lookahead ?=.*.

[Positive lookahead]q(?=u)matches a q that is followed by a u, without making the u part of the match. The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign.

Positive lookahead can be used in this circumstance to match a set of patterns in any order, like so:

(?=.*customer)(?=.*information)(?=.*with)(?=.*overview)(?=.*of)(?=.*sales)

Regular expression visualization

Debuggex Demo Here

To modify, just add, edit or remove words as you see fit.

EDIT

Found a question that explains the same concept here: https://stackoverflow.com/a/3533526/2081889

like image 169
Taylor Hx Avatar answered Sep 18 '22 17:09

Taylor Hx