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.
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);
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
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)));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With