简体   繁体   中英

How to make regular expression only accept special formula?

I'm making html page for special formula using angularJS.

<input ng-model="expression" type="text" ng-blur="checkFormula()" />

function checkFormula() {
  let regex;

  if (scope.formulaType === "sum") {
    regex = "need sum regular expression here"; // input only like as 1, 2, 5:6, 8,9
  } else {
    regex = "need arithmetic regular expression here"; // input only like as 3 + 4 + 6 - 9
  }
  
  if (!regex.test(scope.expression)) {
    // show notification error
    Notification.error("Please input expression correctly");
    return;
  }
  
  // success case
  if (scope.formulaType === "sum") {
     let fields = expression.split(',');
     let result = fields.reduce((acc, cur) => { return acc + Number(cur) }, 0);
     // processing result
  } else {
     // need to get fields with + and - sign.
     // TODO: need coding more...
     let result = 0;
     // processing result
  }
}

So I want to make inputbox only accept my formula. Formulas are two cases.

1,2,3:7,9

or

4-3+1+5

First case, means sum(1,2,3,4,5,6,7,9) and second case means (4-3+1+5).

But I don't know regular expression how to process it. I searched google, but I didn't get result for my case.

So I want to need 2 regex match.

1,2,3:7,9

Fot this pattern, you can try this one :

^\d+(?::\d+)?(?:,\d+(?::\d+)?)*$
  • ^\d+(?::\d+)?

matches string starts with a number(eg 1 ) or two numbers separated by a column (eg 1:2 )

  • (?:,\d+(?::\d+)?)*$

repeats the previous pattern with a comma in front of it as many time as possible until meets the end of the string (eg ,2:3,4:5,6 )


4-3+1+5

Fot this pattern, you can try this one :

^\d+(?:[+-]\d+)*$
  • Like the previous one, this is much simpler

  • ^\d+

starts with a number(eg 12 )

  • (?:[+-]\d+)*$

repeats the previous pattern with a - or + in front of it as many time as possible until meets the end of the string (eg +2-3+14 )


Also, if you need at least one pair of numbers.

Such as 1,2 is allowed but just 1 is not. You can just change the * before $ to + :

^\d+(?::\d+)?(?:,\d+(?::\d+)?)+$
^\d+(?:[+-]\d+)+$

And if you allow white spaces in between them:

^\d+(?:\s*:\s*\d+)?(?:\s*,\s*\d+(?:\s*:\s*\d+)?)+$
^\d+(?:\s*[+-]\s*\d+)+$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM