Compose a regexp for positive and negative integers, floats

Compose a regexp for integers, floats, negative integers.

From a string like this: 2-1+7*-777/-0.001+0.99 I need to get an array:

["2", "1", "7", "-777", "-0.001", "0.99"].

I'm trying to use this code:

var str = "2-1+7*-777/-0.001+0.99";
var array = str.match(/(?:\*|\/|\+|\-)(-\d+(\.\d+)?)|(\d+\.\d+)|(\d+)/g);

But the problem is that the result is:

["2", "1", "7", "*-777", "/-0.001", "0.99"]

Special attention to *-777 and /-0.001

I don't need operation symbols before negative numbers in this array. Only negative (with '-') and positive (without '+') floats and integers.

I don't need to match '-1' in '2-1' but I need to match '-1' in '2*-1'.

Also I need a solution that works not only in Chrome.


This is no dupe of Matching regex for positive and negative numbers with floating point

I am trying to parse numbers out of a calculative term. I need to get the negative sign before a number ONLY if they appear after a division / or multiplication *. The linked answers regex can not do this, it will find all negative numbers.

(Edit: P.Artner from comments to my proposed solution)

2 answers

  • answered 2018-01-14 11:24 yudong shen

    (?<!\d)-?\d+(?:\.\d+)?
    

    (?<!\d)-?: no number behind, and match - if has one

    \d+(?:\.\d+)?:match numbers.

    the above solution only works in chrome currently. i test this one, and it works in Firefox too.

        var regex1 = RegExp(/(^|(?=[*\/\-\+]).+?)(-?\d+(?:\.\d+)?)/,'g');
        var str1 = '2-1+7*-777/-0.001+0.99';
        var array1;
    
    
    while ((array1 = regex1.exec(str1)) !== null) {
      console.log(`${array1[2]}`);
    }
    

  • answered 2018-01-14 11:37 Rizwan M.Tuman

    You may try the following approach:

    (?:[*/](-[\d.]+))|([\d\.]+)
    

    Regex Demo

    const regex = /(?:[*/](-[\d.]+))|([\d\.]+)/g;
    const str = `2-1+7*-777/-0.001+0.99`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
    
    if(m[1]!=null)
    console.log(m[1]);
    else if(m[2]!=null)
    console.log(m[2]);
    
    }
    
    
    //["2", "1", "7", "-777", "-0.001", "0.99"].