KDX2
KDX2

Reputation: 1033

How to Extract Numbers From a Polynomial String (including the + and - signs)

I'm trying to figure out how to extract e.g. -13, as a negative value out of a polynomial, e.g. -13x^2+2-12x^4. So far, I've successfully take out the powers. Additionally, my solution came up to this:

 /\(+)(-)\d{1,4}/g

I know it's wrong syntax, but I'm not sure how to represent the + or - which goes with the following number. It would be good if you can show me how to count the next x like the end of an common/searched phrase, I'm not sure about the term. You know, if it is -3x^ and the point is to extract -3, then it should be like /\ + or - \/d{1,4} x_here/g

Upvotes: 0

Views: 94

Answers (2)

RichS
RichS

Reputation: 943

var formula = '-13x^2+2-12x^4';

formula.match(/[+-]?\d{1,4}/g); 

Returns:

["-13", "2", "+2", "-12", "4"]

If you wish to organize the numbers into coefficients and powers, here's an approach that works:

var formula = '-13x^2+2-12x^4';

function processMatch(matched){
    var arr = [];
    matched.forEach(function(match){
        var vals = match.split('^');
        arr.push({
            coeff: parseInt(vals[0]),
            power: vals[1] != null ? parseInt(vals[1]) : 0
        })
    })
    console.log(arr);
}

processMatch(formula.match(/[+-]?\d+x\^\d+|[+-\s]\d[+-\s]/g))

/* console output:
var arr = [
    { coeff: -13, power: 2 },
    { coeff: 2, power: 0 },
    { coeff: -12, power: 4 }        
];*/

Upvotes: 3

watchdog_timer
watchdog_timer

Reputation: 171

I think you want:

var str = '2x^2-14x+5';
var re = /([+-]?\d{1,4})/g;
var result = str.match(re);

Upvotes: 3

Related Questions