0

I am trying validate a string based on input(textbox.text) regex pattern.

Regex regX = new Regex(TextBox1.Text);

It is failing. But

Regex regX = new Regex(@"\q");

is working fine.

Can you suggest the best way to validate a string based on user regex pattern?

Adi
  • 3
  • 3

1 Answers1

0

You could validate the pattern before using it like this:

public void DoSomething()
{
    string pattern = TextBox1.Text;

    if(IsRegexPatternValid(pattern))
    {
        Regex regX = new Regex(pattern);
    }
    else
    {
        // handle invalid patterns here
        return;
    }
}

public static bool IsRegexPatternValid(String pattern)
{
    try
    {
        new Regex(pattern);
        return true;
    }
    catch { }
    return false;
}

Source for validating: How to validate a Regular Expression?

Your code isnt showing up how you are using the button. But I guess you've bound the KeyDown or TextChanged handlers. In this case validating would be necessary.

Community
  • 1
  • 1
C4d
  • 3,183
  • 4
  • 29
  • 50
  • This is a nice way to skip unsupported regex pattern for the particular language. – Adi Apr 26 '16 at 14:33