Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I test if a regex is valid in C# without throwing exception

Tags:

c#

regex

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.

like image 915
Mark S. Rasmussen Avatar asked Oct 09 '22 03:10

Mark S. Rasmussen


People also ask

How do I know if a regex pattern is valid?

new String(). matches(regEx) can be directly be used with try-catch to identify if regEx is valid. While this does accomplish the end result, Pattern. compile(regEx) is simpler (and is exactly what will end up happening anyway) and doesn't have any additional complexity.

How do you test a RegExp?

To test a regular expression, first search for errors such as non-escaped characters or unbalanced parentheses. Then test it against various input strings to ensure it accepts correct strings and regex wrong ones. A regex tester tool is a great tool that does all of this.

Can C use regex?

A regular expression is a sequence of characters used to match a pattern to a string. The expression can be used for searching text and validating input. Remember, a regular expression is not the property of a particular language. POSIX is a well-known library used for regular expressions in C.

Does C# support regex?

C# provides a class termed as Regex which can be found in System.


2 Answers

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;
}
like image 59
Jeff Atwood Avatar answered Oct 16 '22 16:10

Jeff Atwood


As long as you catch very specific exceptions, just do the try/catch.

Exceptions are not evil if used correctly.

like image 42
Robert Avatar answered Oct 16 '22 15:10

Robert