2010-07-25 43 views
6

tôi cần để tự động xây dựng một Regex để bắt các từ khóa nhất định, nhưLàm thế nào để mã hóa chuỗi cho Cụm từ thông dụng trong .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ó một số loại Regex.Encode mà thực hiện điều này?

Trả lời

8

Bạn có thể sử dụng Regex.Escape. Ví dụ:

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\)) 

Hoặc nếu không có sự LINQ, nhưng sử dụng nối chuỗi trong một vòng lặp (mà tôi cố gắng tránh) theo mã ban đầu của bạn:

string regex = "(some|predefined|words"; 
foreach (Product product) 
    regex += "|" + Regex.Escape(product.Name); 
regex += ")"; 
Các vấn đề liên quan