Can I test if a regex is valid in C# without throwing exception
I allow users to enter a regular expression to match IP addresses, for doing an IP filtration in a related system. I would like to validate if the entered regular expressions are valid as a lot of userse will mess op, with good intentions though.
I can of course do a Regex.IsMatch() inside a try/catch and see if it blows up that way, but are there any smarter ways of doing it? Speed is not an issue as such, I just prefer to avoid throwing exceptions for no reason.
I think exceptions are OK in this case.
Just make sure to shortcircuit and eliminate the exceptions you can:
private static bool IsValidRegex(string pattern)
{
if (string.IsNullOrWhiteSpace(pattern)) return false;
try
{
Regex.Match("", pattern);
}
catch (ArgumentException)
{
return false;
}
return true;
}
As long as you catch very specific exceptions, just do the try/catch.
Exceptions are not evil if used correctly.
Not without a lot of work. Regex parsing can be pretty involved, and there's nothing public in the Framework to validate an expression.
System.Text.RegularExpressions.RegexNode.ScanRegex()
looks to be the main function responsible for parsing an expression, but it's internal (and throws exceptions for any invalid syntax anyway). So you'd be required to reimplement the parse functionality - which would undoubtedly fail on edge cases or Framework updates.
I think just catching the ArgumentException is as good an idea as you're likely to have in this situation.