Replace a MatchCollection items from a string
I have a string containing mathematical expression like:
I want to replace this expression with values of a and b(say a=10,b=20) so that it become:
But when I use Regex.Replace I get:
How can I replace the values of a and b at correct places.
I have filterd out MatchCollection object that contains:
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.
Use boundary \b:
\b The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character.
"them theme" "them them" in "them theme them them"
so that use:
Regex.Replace(inputString, @"(\bb\b)", "20"); Regex.Replace(inputString, @"(\ba\b)", "10");
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);
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
- Variable must have binary operator(+,-,*,/) and optinally spaces to its right(if start) ,to its left(if end) or on both side. It can also have paranethis around it if passed in function. So create a regex which satisfies these all conditions
You can do with this:
And then use the same way for b with replacement of 20