Replace a MatchCollection items from a string

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}

Answers


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.

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");

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

  1. 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:

Regex Example

And then use the same way for b with replacement of 20


Need Your Help

Moq Exception: Verifying a method call that takes parameters

asp.net-mvc unit-testing testing moq

I want to test that the "Create" method on the _eventManager in my controller gets called. When I run my test, I get the following exception:

Quickbooks Desktop: Billable status is not applicable for the specified Account type

java php quickbooks intuit-partner-platform quickbooks-online

I have attempted to submit the following request content to Quickbooks Desktop by using v3 QB REST API