c# – 如何在.NET中为正则表达式编码字符串?

我需要动态构建一个 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 += ")";

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...