tags:

views:

46

answers:

1

I need to dynamically build a Regex to catch the given keywords, like

string regex = "(some|predefined|words";
foreach (Product product in products)
    regex += "|" + product.Name; // Need to encode product.Name because it can include special characters.
regex += ")";

Is there some kind of Regex.Encode that does this?

+4  A: 

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 += ")";
Jon Skeet