Casey Sebben
Casey Sebben

Reputation: 677

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

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.

Upvotes: 8

Views: 267

Answers (4)

NeverHopeless
NeverHopeless

Reputation: 11233

You can also use Array.FindAll method. See the example in the link.

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44316

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);

Upvotes: 13

Ria
Ria

Reputation: 10357

A simple idea without LINQ:

var st = "CAR BIG RED".Split(' ');
var sm = "I have a BIG RED CAR";
bool res = true;
foreach (string s in st)
    res &= sm.Contains(s);

Upvotes: 0

sa_ddam213
sa_ddam213

Reputation: 43636

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

Upvotes: 4

Related Questions