简体   繁体   English

在C#中验证正则表达式是否形成良好的最简单方法是什么?

[英]What is the easiest way in C# to validate if a regular expression is well formed?

Is there any simple way in C# to test if a regular expression is a regular expression? 在C#中有没有简单的方法来测试正则表达式是否是正则表达式? In other words, I would like to check if a user-provided regex pattern is malformed or not. 换句话说,我想检查用户提供的正则表达式模式是否格式错误。 This is purely a syntax test and not what the regex is supposed to achieve/test. 这纯粹是一种语法测试,而不是正则表达式应该实现/测试的内容。 Thanks 谢谢

您可以尝试将其传递给Regex构造函数并捕获可能的ArgumentException ,如果参数是格式错误的正则表达式,则抛出该ArgumentException

Here's an example from C# Online .NET that uses exceptions: 以下是C#Online .NET中使用异常的示例:

EDIT: 编辑:

Removed the code to respect copyright owners, just in case. 为了以防万一,删除了尊重版权所有者的代码。 Simply click on the above link to see it. 只需点击上面的链接即可查看。

I have to say, this doesn't sound good. 我不得不说,这听起来不太好。 The extremely small subset of computer users that would be capable of correctly entering a regex should probably also be trusted to interpret the exception message correctly. 能够正确输入正则表达式的极小数量的计算机用户也应该被信任正确解释异常消息。 Trying to validate their entry and getting it wrong would be sufficient grounds for them to get pretty flipping mad and uninstall your program. 试图验证他们的输入并将其弄错将足以让他们变得非常疯狂并卸载您的程序。

If experienced programmers are not actually your target customer, be sure to avoid regex. 如果有经验的程序员实际上不是您的目标客户,请务必避免使用正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM