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

时间:2022-10-24 14:07:20

Is there any simple way in C# to test if a regular expression is a regular expression? 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

在C#中有没有简单的方法来测试正则表达式是否是正则表达式?换句话说,我想检查用户提供的正则表达式模式是否格式错误。这纯粹是一种语法测试,而不是正则表达式应该实现/测试的内容。谢谢

3 个解决方案

#1


5  

You may try passing it to the Regex constructor and catch potential ArgumentException which is thrown if the argument is a malformed regular expression.

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

#2


2  

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.

为了以防万一,删除了尊重版权所有者的代码。只需点击上面的链接即可查看。

#3


1  

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.

如果有经验的程序员实际上不是您的目标客户,请务必避免使用正则表达式。

#1


5  

You may try passing it to the Regex constructor and catch potential ArgumentException which is thrown if the argument is a malformed regular expression.

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

#2


2  

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.

为了以防万一,删除了尊重版权所有者的代码。只需点击上面的链接即可查看。

#3


1  

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.

如果有经验的程序员实际上不是您的目标客户,请务必避免使用正则表达式。