Saurabh Kumar
Saurabh Kumar

Reputation: 154

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}

Upvotes: 0

Views: 1211

Answers (5)

Ria
Ria

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

Vishal Suthar
Vishal Suthar

Reputation: 17194

You can do with this:

Regex Example

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

Upvotes: 0

ZafarYousafi
ZafarYousafi

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

  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

Upvotes: 0

x2.
x2.

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

nhahtdh
nhahtdh

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

Related Questions