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\
Or without LINQ, but using string concatenation in a loop (which I am trying to avoid) according to your source code:
string regex = "(some|predefined|words"; foreach (Product product) regex += "|" + Regex.Escape(product.Name); regex += ")";
Jon skeet
source share