I have a calculator and I want it to not start calculation until the expression seems to be correct. Seems to be correct means that it should not contain any non math symbols like $
, #
etc.
I don't care about logical validity as paretheses balancing or missing operands, just invalid characters.
I use server-client approach.
To accomplish this I want to use regex (it could be provided with list of available operations).
For example:
- 3 + 10 - correct
- tan(45 * PI / 180) - correct
- 5 % 10 - correct
- 3 + # - incorrect
- 3 + correct
- 5 + 3 * ( 2 - also correct, symbols are perfectly valid
I tried to use regex that uses available operations' symbols, but here some complications I encountered:
- Operation's symbol's length can vary. It could be either one symbol or a function name, therefore it's needed somehow to split apart those two cases in order to make regex work corerct.
I was using groups: [\+\-tan] will not work as intented, because it will match any letter from
tan
, but I need to only match the wholetan
part. - As for me, depending on available operations seems to be not such a good idea, I need more general way to test expression in case I want to use it elsewhere.
- The main problem with my regex was that should it encounter only one character from regex and then it will tell that it's correct despite of possible invalid following characters.