You can use Regex.Escape
. For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
public class Test
{
static void Main()
{
string[] predefined = { "some", "predefined", "words" };
string[] products = { ".NET", "C#", "C# (2)" };
IEnumerable<string> escapedKeywords =
predefined.Concat(products)
.Select(Regex.Escape);
Regex regex = new Regex("(" + string.Join("|", escapedKeywords) + ")");
Console.WriteLine(regex);
}
}
Output:
(some|predefined|words|\.NET|C\#|C\#\ \(2\))
Or without the LINQ, but using string concatenation in a loop (which I try to avoid) as per your original code:
string regex = "(some|predefined|words";
foreach (Product product)
regex += "|" + Regex.Escape(product.Name);
regex += ")";