34

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?

1
  • 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 :) Commented Aug 17, 2011 at 15:24

5 Answers 5

68

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 "";
}
Sign up to request clarification or add additional context in comments.

Comments

12

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.

2 Comments

.NET has it too, it's Regex.Compile.
Does it? Isn't it Regex.CompileToAssembly? learn.microsoft.com/en-us/dotnet/api/…
8

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

[0-9]++

1 Comment

This is a valid regEx.
2

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

BOOM\

Comments

1

If you want to test, if it works properly, you need to test it with valid and invalid patterns, which should be done using a unit test framework like NUnit.

It is also possible to display a more detailed error message, as also proposed in the C# Cookbook; see the chapter 8.3. Verifying the Syntax of a Regular Expression

Here is a simple example class with some test data (also available on .Net Fiddle, where you can run it right away in your browser)

using System;
using System.Text.RegularExpressions;
                    
public class Program
{
    public static Boolean validateRegEx(String pattern) 
    {   
        if (pattern == null || pattern.Length == 0) 
        {
            System.Console.Out.WriteLine("RegEx '{0}' is NOT valid. The pattern may not be empty or null.", pattern);
            return false;
        }
        
        try 
        { 
            new Regex(pattern);
            System.Console.Out.WriteLine("RegEx '{0}' is valid.", pattern);
            return true;
        }
        catch (ArgumentException ex) If 
        {
            System.Console.Out.WriteLine("RegEx '{0}' is NOT valid: {1}", pattern, ex.Message);
            return false;
        }
    }
    
    public static void Main()
    {
        // Invalid regular expressions:
        validateRegEx(""); // The pattern may not be empty or null.
        validateRegEx(null); // The pattern may not be empty or null.
        validateRegEx("**"); // Quantifier {x,y} following nothing.
        validateRegEx("\\"); //  Illegal \ at end of pattern.
        validateRegEx("AABB???"); // Nested quantifier ?.
        validateRegEx("AA(C(B)A"); // Not enough )'s.
        validateRegEx("AA(C)B)A"); // Too many )'s.

        // Valid regular expressions:
        validateRegEx("A"); // 'A' is valid.
        validateRegEx(".*ABA.?"); // '.*ABA.?' is valid.
        validateRegEx("AB?A"); // 'AB?A' is valid.
        validateRegEx("AB*A"); // AB*A' is valid.
        validateRegEx("A(BB){1,4}"); // 'A(BB){1,4}' is valid.
        // ...
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.