Home > database >  How do I prevent regular rexpressions from replacing the first instance of a pattern match with the
How do I prevent regular rexpressions from replacing the first instance of a pattern match with the

Time:05-31

I am certain there might be something that answers this directly if this is what I'm searching for. Now, I know I need to comment things a little bit better and the style probably could use some work, so be gentle please. If you can just point me to a thread where the same problem has been answered, I'd appreciate it. (I've tried to look for one, but I'm no sure I'm using the right search terms.)

Here is the code:

    // Evaluate 5x style expressions and replace with * ivalue.
    eqvalue = eqvalue.replace(/-?[0-9]*[Xx]/g, eqvalue.match(/-?[0-9]*/)   "*"   ivalue);
    dvalue = dvalue.replace(/-?[0-9]*[Xx]/g, dvalue.match(/-?[0-9]*/)   "*"   ivalue);
    
    // Now do the same for naked polynoials like x^2   x   3
    eqvalue = eqvalue.replace(/[Xx]/g, ivalue);
    dvalue = dvalue.replace(/Xx/g, ivalue);

What I am trying to do is to convert a polynomial into a string that I can run though the eval function. Basically, if the user enters 5x^2 x 5 into a box, I want this to be replaced with something like 5*2.9 2.9 5.

So far, if I'm entering a string like 5x^2 15x 295, I'm getting 5*2.9 5*2.9 295, and this i not what I want.

I'm getting this instead: enter image description here

How do I alter the regular expressions to get them to not substitute the first value they run across?

(Also, don't worry. The calculus class is over. I promised the professor not to program a Newton's Method after the course, because he did not like the idea of me writing a Reimann sum's calculator. A B- was the final grade in the course.)

CodePudding user response:

The answer suggested by Jay works fine except for mixed-cases like this "5x^2 x 5", in this case after replacement your string will be like this: "5 * x^2 * x 5", which is not a valid expression. Do this, to obtain a completely valid expression:

dvalue = dvalue.replace(/(-?[0-9]*)[Xx]/g, "$1*"   ivalue);
dvalue = dvalue.replace(/\ \s*\*/g, " ");

CodePudding user response:

Instead of using .match(), you can define a matching group using ( and ) in the replace expression and refer to its contents with $1 in the replacement:

dvalue = "5x^2   15x   x   295";
ivalue = 2.9;

// add missing multiplication signs before x
dvalue = dvalue.replace(/(-?[0-9] )[Xx]/g, "$1*x");
// replace x with ivalue
dvalue = dvalue.replace(/[Xx]/g, ivalue);

Result:

"5*2.9^2   15*2.9   2.9   295"

EDIT: Adjusted based on Charchit's feedback.

  • Related