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.R
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.
// ...
}
}