Home > Blockchain >  Check multiple words match with Regex
Check multiple words match with Regex

Time:12-23

I'm looking for a RegExp that checks if 2 or more words are present in a string regardless of their order.

If I want to find the words "dog" and "cat", the expression must find a match only when they are both in the sentence:
"I like dogs" - no match
"I love cats" - no match
"I own a dog and a cat" - ok

CodePudding user response:

The regular expression pattern in this example will match both "dog" and "cat" in a sentence. It does this by using alternation with the | operator, which allows either "dog" or "cat" to appear in the first and second positions. This means that the pattern will match sentences such as "I own a dog and a cat" and "I own a cat and a dog".

Demo: https://dotnetfiddle.net/pU2HhD

Implementation:

public class Program
{
    public static void Main()
    {
        List<string> sentences = new List<string>
        {
            "I like dogs",
            "I love cats",
            "I own a dog and a cat",
            "I own a cat and a dog"
        };
        
        string pattern = @"\b(dog|cat)\b.*\b(dog|cat)\b";
        
        foreach (var sentence in sentences) 
        {
            Match match = Regex.Match(sentence, pattern);
            if (match.Success)
                Console.WriteLine($"{sentence} - ok");
            else
                Console.WriteLine($"{sentence} - no match");
        }
    }
}

Output:

I like dogs - no match
I love cats - no match
I own a dog and a cat - ok
I own a cat and a dog - ok

CodePudding user response:

^.*(dog).*(cat)|.*(cat).*(dog).*$

this should do the trick.

.*(dog).*(cat) the first part checks if the string contains "dog" before "cat"

.*(cat).*(dog).* the second part checks if the string contains "cat" before "dog"

| is a logic operator for OR

^ and $ are anchors and match the start and the end

  • Related