2010-07-25 6 views
6

Je dois construire dynamiquement un Regex pour attraper les mots-clés donnés, commeComment encoder des chaînes pour l'expression régulière dans .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 += ")"; 

Y at-il une sorte de Regex.Encode qui fait cela?

Répondre

8

Vous pouvez utiliser Regex.Escape. Par exemple:

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

Sortie:

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

ou sans LINQ, mais en utilisant la concaténation de chaîne dans une boucle (que j'essaie d'éviter) selon votre code d'origine:

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