c# – 如何在.NET中为正则表达式编码字符串?
发布时间:2020-12-15 08:21:05 所属栏目:百科 来源:网络整理
导读:我需要动态构建一个 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来捕获给定的关键字,比如
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 += ")"; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |