var formula = '-13x^2+2-12x^4';
formula.match(/[+-]?\d{1,4}/g);
返回:
["-13", "2", "+2", "-12", "4"]
如果您希望將數字組織成係數和權力,可以採用以下方法:
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 }
];*/
'(+ | - )'........... – zerkms
@zerkms取決於我是使用新的RegExp()類還是普通的=/things /模式,因爲現在它看起來像這樣: sc = str_input.match'(/(+ | - )\ d {1,4}/g)'指出錯誤...無效的語法,確實 – KDX2
Escape'+'as '\ +' – zerkms