How to escape all regex characters automatically using built-in .NET mechanism or something like that?
I am using Regex class to find match for a regular expression. See example below.
string pattern = "abc";
Regex regexp = new Regex(@"a\w", RegexOptions.None);
if (regexp.IsMatch(pattern))
{
MessageBox.Show("Found");
}
So, here Found will hit.
Now, in some cases, I still want to use Regex class but treat Regular Expression as plain string. So, for example, I will change pattern string to @”a\w” and need Regex class should find the match.
string pattern = @"a\w";
Regex regexp = new Regex(@"a\w", RegexOptions.None);
if (regexp.IsMatch(pattern))
{
MessageBox.Show("Found");
}
In the above case also, “Found” should hit.
So, the question is how to convert or treat Regular Expression into/as a plain string or something like that which can be used in a Regex Class? How to achieve the above code snippet scenario?
Note: – I do not want to use string.Contains, string.IndexOf, etc for plain text string matching.
You can “de-regex” your string through Regex.Escape. This will transform your pattern-to-search-for into the correctly escaped regex version.