create a regular expression that determines if a string contains all terms from a given set in any order in csharp

Here's an example of a regular expression that can be used to determine if a string contains all terms from a given set in any order:

main.cs
string termSet = "(term1|term2|term3)";
string inputString = "This is a string that contains term3, term2, and term1 in any order.";

// Create the regular expression pattern
string pattern = string.Format("^(?=.*{0})", termSet);

// Append a positive lookahead for each term in the termSet
foreach (string term in termSet.Split('|'))
{
    pattern = string.Concat(pattern, "(?=.*\\b", term, "\\b)");
}

// Test if the input string matches the pattern
bool isMatch = Regex.IsMatch(inputString, pattern);

if (isMatch)
{
    Console.WriteLine("The input string contains all terms from the given set.");
}
else
{
    Console.WriteLine("The input string does not contain all terms from the given set.");
}
703 chars
24 lines

In this example, we use a positive lookahead to check for each term in the term set. The \\b characters are used to match word boundaries, which ensures that we only match complete terms and not partial matches within larger words.

gistlibby LogSnag