开发者

How to treat Regular Expression as plain text while using .Net Regex Class?

开发者 https://www.devze.com 2023-03-24 10:47 出处:网络
How to escape all reg开发者_如何转开发ex characters automatically using built-in .NET mechanism or something like that?

How to escape all reg开发者_如何转开发ex 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.

string pattern = @"a\w";
Regex regexp = new Regex(Regex.Escape(@"a\w"), RegexOptions.None);
if (regexp.IsMatch(pattern))
{
    MessageBox.Show("Found");
}


In the second case you don't want to search for what \w means in regex, you want to search for the literal \w, so you'd want:

string pattern = @"a\w";
Regex regexp = new Regex(@"a\\w", RegexOptions.None);
if (regexp.IsMatch(pattern))
{
    MessageBox.Show("Found");
}

(Note the escaping).


You just need to escape your special characters like: @"a\\w"

0

精彩评论

暂无评论...
验证码 换一张
取 消