skip to Main Content

I need to extract numbers from the string for that I have preferred the following regix

var str = "1 1/2 percentage";
var n = str.match(/[0-9]+([/.]d+)?/g);
console.log(n);

But I am not able to restrict negative numbers in the string .

Valid Scenario:

"1.5 % dividend applied"
"1 1/2 percentage"
 "1/10 percentage"
"2.5 percentages"
"10% dividend"
"10 percentages applied"

Invalid Scenario:

"-1 1/2 percentage"
"-1.5 % dividend applied"
"-10% dividend"

Code suggestion will be appriciated.Thank you

2

Answers


  1. With a mix of javascript and regex:

    function getNumbers(text) {
        //match all numbers
        var matches = text.match(/-?d+([/.]d+)?/g);
        var res = [];
    
        for (var i = 0; i < matches.length; i++) {
            var match = matches[i];
    
            if (!match.startsWith('-')) { // check if its not a negative number
                result.push(match);
            }
        }
    
        return res;
    }
    
    Login or Signup to reply.
  2. You need:

    /(?<![-.d])d+([/.]d+)?/g
    

    Explanation:

    (?<![-.d])   # Match something that is not preceded by '-', '.' or a digit,
    d+           # starts with 1+ digits, and
    ([/.]d+)?   # ends with either a '/' or a '.' followed by 1+ digits
    

    Try it on regex101.com.

    Try it:

    console.config({ maximize: true });
    
    const testcases = [
      '1.5 % dividend applied',
      '1 1/2 percentage',
      '1/10 percentages',
      '2.5 percentages',
      '10% dividend',
      '18.6 foo',
      '10 percentages applied',
      '-1 1/2 percentage',
      '-1.5 % dividend applied',
      '-10% dividend',
      '-18.6 foo'
    ];
    
    const regex = /(?<![-.d])d+([/.]d+)?/g;
    
    for (const testcase of testcases) {
      console.log(`'${testcase}'`, testcase.match(regex) ?? 'no match');
    }
    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search