Creating dynamic regex patterns in C #

I am trying to create a regex pattern with some parts of the pattern extracted from the database.

for example

string pt= "@\"\\b(" + db.GetPattern + ")\\b\"";        
Regex regex = new Regex(pt, RegexOptions.IgnoreCase | RegexOptions.Compiled);
return regex.Replace(input, "*");

Although I tried to avoid this, I could not get it to work. If I create the template manually as

Regex regex = new Regex(@"\b(test|test2)\b", RegexOptions.IgnoreCase | RegexOptions.Compiled);
return regex.Replace(input, "*");

It works great.

+5
source share
1 answer

Try

string pt = @"\b(" + db.GetPattern + @")\b";

or alternatively:

string pt = string.Concat(@"\b(", db.GetPattern, @")\b");

, , , , , . , , @"foo", #, . @"\b" "\\b" , , # escape-. , # , .

:

@"\b(test|test2)\b"

\b(test|test2)\b

, , @ , . , .

+18

All Articles