Check math expressions with regex?

I want to test math expressions using a regular expression. The mathematical expression may be this

  • It may be empty, nothing is entered

  • If specified, it will always start with the operator + or - or * or / , and it will always be followed by a number that can have any number of digits and a number can be decimal (contains . Between numbers) or an integer (no character inside the room). examples: *0.9 , +22.36 , - 90 , / 0.36365

  • Then may follow what is mentioned in paragraph 2 (above the line). examples: *0.9+5 , +22.36*4/56.33 , -90+87.25/22 , /0.36365/4+2.33

Please help me.

+6
source share
2 answers

Something like this should work:

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

Regexr Demo

  • ^ - start of line
  • [-+/*] - one of these operators
  • \d+ - one or more numbers
  • (\.\d+)? - an optional point followed by one or more numbers
  • ()* - the whole expression is repeated zero or more times
+12
source

If you want a negative or positive expression, you can write it like this> ^\-?[0-9](([-+/*][0-9]+)?([.,][0-9]+)?)*?$

And the second - ^[(]?[-]?([0-9]+)[)]??([(]?([-+/*]([0-9]))?([.,][0-9]+)?[)]?)*$

With a parenthesis in the expression, but not counting the number, you will need a method that checks it or the regular expression. // method

  public static bool IsPairParenthesis(string matrixExpression) { int numberOfParenthesis = 0; foreach (char character in matrixExpression) { if (character == '(') { numberOfParenthesis++; } if (character == ')') { numberOfParenthesis--; } } if (numberOfParenthesis == 0) { return true; } return false; } 
-1
source

Source: https://habr.com/ru/post/917933/


All Articles