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.
As long as you catch very specific exceptions, just do the try/catch.
Exceptions are not evil if used correctly.
I think exceptions are OK in this case.
Here's what I put together:
private static bool IsValidRegex(string pattern)
{
if (string.IsNullOrEmpty(pattern)) return false;
try
{
Regex.Match("", pattern);
}
catch (ArgumentException)
{
return false;
}
return true;
}