我需要动态构建一个
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 += ")";
原文地址:https://www.jb51.cc/csharp/243263.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。