Reputation: 889
I have to build a filter expression dynamically. That's why I would like to match and replace filter. For example I have the following string:
string input = " (Country = \"Brazil\" OR Country = \"Canada\") AND CompanyName.Contains(\"Contoso\") ";
I want to replace, CompanyName.Contains(\"Contoso\") where Company Name may have different name.
Here is my code:
string input = " (Country = \"Brazil\" OR Country = \"Canada\") AND CompanyName.Contains(\"Contoso\") ";
string replacement = "123456";
string pattern = @"(CompanyName.Contains\()";
// \"[^\"]*\"
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine(result);
It seems that my filter expression is wrong. What it should be?
Upvotes: 1
Views: 76
Reputation: 626794
In your expression, the dot is not escaped and it only matches part of the required CompanyName.Contains("Contoso")
stopping right after the opening (
.
You can use
var pattern = @"\bCompanyName\.Contains\([^()]*\)";
See the regex demo
The \b
matches a word boundary, an escaped dot matches a literal dot and \([^()]*\)
matches a (
followed with 0+ characters other than (
and )
(due to the negated character class [^()]
).
Upvotes: 1