I am working on a regex search and replace program and would like to have a real-time preview that shows any change immediately.
My problem is that the program logically crashes when I open a "[" bracket, for example, because Regex expects a bracket to be closed. Of course, there may be other errors where the program crashes during a search.
I would like to stop the search and display an error message if the pattern is wrong.
Does anyone know of a solution to use an "IF" query in C#, for example, to check if a regex search would work before executing it?
Or how else can I get by without crashing? ^^'
using System.Text.RegularExpressions;
public string UseRegex(string input, string search, string replace)
{
if (???)
{
string result = Regex.Replace(input, search, replace);
return result;
}
else
{
return "error";
}
}
CodePudding user response:
Try this:
public string UseRegex(string input, string search, string replace)
{
try
{
string result = Regex.Replace(input, search, replace);
return result;
}
catch
{
return input;
}
}