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.