An invalid regex pattern

22,857

Solution 1

This is invalid...

[

You can also test the validity of regular expressions in real-time at http://regexhero.net/tester/

By the way, you don't actually have to test the regular expression against a string to see if it's valid. You can simply instantiate a new Regex object and catch the exception.

This is what Regex Hero does to return a detailed error message...

public string GetRegexError(string _regexPattern, RegexOptions _regexOptions)
{
    try
    {
        Regex _regex = new Regex(_regexPattern, _regexOptions);
    }
    catch (Exception ex)
    {
        return ex.Message;
    }

    return "";
}

Solution 2

Try this:

*

BTW, in Java there is a method to compile a string to a pattern and it throws an exception with precise error diagnostic.

Solution 3

Here's an example of a non-correct expression:

[0-9]++

Solution 4

Here's another one. Anything that ends in a single backslash (dangling backslash) is invalid.

BOOM\
Share:
22,857

Related videos on Youtube

Marcom
Author by

Marcom

Full stack Developer.. Specializing on c#, work on web, mobile, server applications and been playing a bit with F#, Python and machine learning

Updated on October 03, 2020

Comments

  • Marcom
    Marcom over 3 years

    I have a piece of code in c# that checks, if a value is a valid regex pattern.

    Code is straight forward:

       try
       {
          System.Text.RegularExpressions.Regex.IsMatch("", pattern);
       }
       catch (Exception ex)
       {
           return "pattern matches must be a valid regex value";
       }
    

    I'm trying to test if it works correctly, but I can't find an invalid regex pattern.

    Any suggestions?

    • Patrik
      Patrik almost 13 years
      I would say try{System.Text.RegularExpressions.Regex.IsMatch("", pattern);}catch (Exception){return "pattern matches must be a valid regex value";} but that's a correct expression :)
  • Blindy
    Blindy almost 13 years
    .NET has it too, it's Regex.Compile.
  • Attila
    Attila over 3 years
    Does it? Isn't it Regex.CompileToAssembly? docs.microsoft.com/en-us/dotnet/api/…
  • Max M
    Max M almost 3 years
    This is a valid regEx.