2010-07-25 9 views
6

Ho bisogno di costruire dinamicamente un Regex per catturare le parole chiave indicate, comeCome codificare le stringhe per l'espressione regolare in .NET?

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

C'è una sorta di Regex.Encode che fa questo?

risposta

8

È possibile utilizzare Regex.Escape. Per esempio:

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); 
    } 
} 

uscita:

(some|predefined|words|\.NET|C\#|C\#\ \(2\)) 

o senza LINQ, ma usando concatenazione di stringhe in un ciclo (che cerco di evitare) secondo il vostro codice originale:

string regex = "(some|predefined|words"; 
foreach (Product product) 
    regex += "|" + Regex.Escape(product.Name); 
regex += ")"; 
Problemi correlati