2010-07-25 16 views
6

.NET'te Normal İfade için dizeleri nasıl kodlanır?

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

gibi belirli anahtar kelimeleri yakalamak için dinamik olarak bir Regex oluşturmam gerekiyor. Bunu yapan bir çeşit Regex.Encode var mı?

cevap

8

Regex.Escape'u kullanabilirsiniz. Örneğin:

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

Çıktı:

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

Veya LINQ olmadan

, ancak orijinal kod uyarınca (I kaçınıyorum olan) bir döngü içinde dize birleştirme kullanarak:

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