Reputation: 154
I have a string containing mathematical expression like:
strExpression= a+b+tan(a)+tan(b)+a+b
I want to replace this expression with values of a and b(say a=10,b=20) so that it become:
10+20+tan(10)+tan(20)+10+20
But when I use Regex.Replace
I get:
10+20+t10n(10)+t10n(20)+10+20
How can I replace the values of a and b at correct places.
I have filterd out MatchCollection object that contains:
{a},{b},{tan},{a},{tan},{b},{a},{b}
Upvotes: 0
Views: 1211
Reputation: 10347
Use boundary \b
:
\b The match must occur on a boundary
between a \w (alphanumeric) and a \W (nonalphanumeric) character.
for example:
\b\w+\s\w+\b
result is
"them theme" "them them" in "them theme them them"
so that use:
Regex.Replace(inputString, @"(\bb\b)", "20");
Regex.Replace(inputString, @"(\ba\b)", "10");
Upvotes: 1
Reputation: 17194
You can do with this:
And then use the same way for b
with replacement of 20
Upvotes: 0
Reputation: 10880
Try to be more specific in your regex rather than just replacing the values. Here are some rules which describes whether a character captured is variable or not
Upvotes: 0
Reputation: 9668
string expression = "strExpression= a+b+tan(a)+tan(b)+a+b";
expression = Regex.Replace(expression, @"\ba\b", "10");
expression = Regex.Replace(expression, @"\bb\b", "20");
Console.WriteLine(expression);
Upvotes: 0
Reputation: 56819
You can use word boundary \b
before and after the variable name (e.g. \ba\b
for variable a
and \bb\b
for variable b
) to match the variable in the expression.
Upvotes: 1