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? In other words, I would like to check if a user-provided regex pattern is malformed or n开发者_如何学Goot. This is purely a syntax test and not what the regex is supposed to achieve/test. Thanks
You may try passing it to the Regex constructor and catch potential ArgumentException which is thrown if the argument is a malformed regular expression.
Here's an example from C# Online .NET that uses exceptions:
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.
精彩评论