Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the optimal way to find words in a string in any order with regex in C#?

Tags:

c#

regex

So I have a string " I have a BIG RED CAR"

I want a user to be able to put in part of the string in any order. So they can write "CAR BIG RED" and the string will be found. I know I can do this by doing multiple IsMatch calls with a Regex string or I could use one string with anchors such as "^(?=.*CAR)(?=.*RED)(?=.*BIG).*$". I was wondering what would be the best option or is there an even better option?

Note: I am using C#, so any .net regex should work. All suggestions are welcome.

like image 741
Casey Sebben Avatar asked May 27 '13 03:05

Casey Sebben


2 Answers

Stepping outside the realm of Regex, you could do something like this:

string s = "I have a BIG RED CAR";

var searchTerms = "CAR BIG RED".Split(' ').ToList();
var hasTerms = searchTerms.All(s.Contains);
like image 184
Keith Nicholas Avatar answered Oct 23 '22 02:10

Keith Nicholas


You could just check the words in the String against the words in the search String.

you could use Linq for this if you want

Linq:

List<string> items = new List<string>
{
    "I have a BIG RED CAR",
    "I have a BIG GREEN TRUCK", 
    "I have a BIG YELLOW BOAT"
};

string searchString = "CAR BIG RED";
string result = items.FirstOrDefault(x => searchString.Split(' ').All(s => x.Split(' ').Contains(s)));

Regex:

With RegEx you could concatenate all the individual words into a pipe delimited string and use with the \b operator to check for the whole words.

string sentance = "I have a BIG RED CAR";
string searchString = "CAR BIG RED";

string regexPattern = string.Format(@"\b({0})\b", searchString.Replace(" ","|"));
if (Regex.IsMatch(sentance, regexPattern))
{
    // found all search words in string
}

However there couild be a nicer way to do this with RegEx, I only know the basics of RegEx

like image 42
sa_ddam213 Avatar answered Oct 23 '22 04:10

sa_ddam213