我需要动态构建一个
Regex来捕获给定的关键字,比如
- 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 += ")";
是否有某种Regex.Encode可以做到这一点?
解决方法
您可以使用
Regex.Escape
.例如:
- 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);
- }
- }
输出:
- (some|predefined|words|\.NET|C\#|C\#\ \(2\))
或者没有LINQ,但是根据原始代码在循环中使用字符串连接(我试图避免):
- string regex = "(some|predefined|words";
- foreach (Product product)
- regex += "|" + Regex.Escape(product.Name);
- regex += ")";