Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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(e.g. 1) or two numbers separated by a column (e.g. 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 (e.g. ,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(e.g. 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 (e.g. +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+)+$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...