tags:

views:

153

answers:

3

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

+5  A: 

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

Darin Dimitrov
+2  A: 

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.

Andy West
+1  A: 

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.

Hans Passant
Are you saying that the application should not handle the exception? (which would cause it to terminate)? That sounds even worse to me.
Andy West
I agree, but unfortunately I cannot change the requirements. This is used for a business rules engine that's configurable by the user and regex is only used to cover some potential edge cases.
@zoman - wow, that doesn't sound good. Business rulez are not entered by programmers. Thus the need to validate the regex, no doubt. The next failure mode is that a valid regex just doesn't filter right, but that's not your team's problem. Customer happiness is still zero. Show this post to your astronaut architect, that's all I can do. Good luck with it.
Hans Passant