pick strings that contain all the terms 'cat', 'dog' and 'bird' only once in any order in csharp

You can use regular expressions and LINQ to check if the string contains all the terms 'cat', 'dog' and 'bird' only once in any order. Here's an example code:

main.cs
using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string input = "I have a cat, a dog, and a bird.";
        bool containsAllTerms = Regex.IsMatch(input, @"\bcat\b.*\bdog\b.*\bbird\b|\bbird\b.*\bdog\b.*\bcat\b");

        if (containsAllTerms)
        {
            Console.WriteLine("The input string contains all the terms 'cat', 'dog' and 'bird' only once in any order.");
        }
        else
        {
            Console.WriteLine("The input string does not contain all the terms 'cat', 'dog' and 'bird' only once in any order.");
        }
    }
}
645 chars
22 lines

The regular expression @"\bcat\b.*\bdog\b.*\bbird\b|\bbird\b.*\bdog\b.*\bcat\b" matches any string that contains the terms 'cat', 'dog' and 'bird' only once in any order. The \b denotes word boundaries to ensure that only complete words are matched.

The LINQ method Regex.IsMatch(input, pattern) returns true if the input string matches the regular expression pattern.

Note that this approach assumes that the terms 'cat', 'dog' and 'bird' only appear once in the input string. If they could appear multiple times, you'll need to modify the regular expression accordingly.

gistlibby LogSnag