如何在.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 += ")";
是否有某种 Regex.Encode 可以做到这一点?
I need to dynamically build a Regex to catch the given keywords, like
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 += ")";
Is there some kind of Regex.Encode that does this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
Regex.Escape
。例如:
输出:
或者不使用 LINQ,但按照原始代码在循环中使用字符串连接(我试图避免):
You can use
Regex.Escape
. For example:Output:
Or without the LINQ, but using string concatenation in a loop (which I try to avoid) as per your original code: