Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert character before specific character c#

Tags:

string

c#

regex

Assuming the string below is in C#, how would one replace

y=x^7+3x^4-x+5

with

y=0^7+3*0^4-0+5

as one cannot just replace all instances of x with 0 as then you get 30^4

like image 851
Spartan Avatar asked Aug 08 '26 20:08

Spartan


1 Answers

var a = "y=x^7+3x^4-x+5";
var b = Regex.Replace(a, @"(\d+|[a-zA-Z])(?=\d+|[a-zA-Z])", @"$1*");
var c = Regex.Replace(b, @"x", @"0");

summery of 2nd line: match any number or variable followed by any number or variable.

Output examples:

In: y=33xggyz/3/4*x/x+xx1         |  In: y=x^7+3x^4-x+5        
Out:y=33*x*g*g*y*z/3/4*x/x+x*x*1  |  Out:y=0^7+3*0^4-0+5              
                                  |
In: y=2+33xggyz/3/4*x/x+xx        |  In: y=x1
Out:y=2+33*0*g*g*y*z/3/4*0/0+0*0  |  Out:y=0*1
                                  |
In: y=10xy^2+xx+(12x+1yy)         |  In: y(xx)=1
Out:y=10*0*y^2+0*0+(12*0+1*y*y)   |  Out:y(0*0)=1

Updated: (7/4/2015) fixed bug, failed with y=x1 (did return y=01)

like image 155
SunsetQuest Avatar answered Aug 11 '26 10:08

SunsetQuest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!