I'm trying to render a react input element that can either take in a number or a string with BODMAS operations like (5*3)+8 and evaluate it. I would like to first valid the BODMAS string so I'm trying to come up with a regular expression that validates that the string is valid, for example it catches something with a missing parentheses like (5*3 +8
I have two expressions so far
const regex = /^(?:\s*\d+(?:\s*[+*/-]\s*\d+)*\s*)$/;
This one wont validate something like (5+30)*8 while the other
const regex2 = /^\(*(\d+(\.\d+)*|\((\d+(\.\d+)*|\(*(\d+(\.\d+)*|\((\d+(\.\d+)*|[\+-\/\*]))*\)*)*\)*)*[\+-\/\*]*)+\)*$/
This one returns as invalid. I'm new to regex and I think there's something I may be missing.
The best way would be to use a parser.
But if you prefer, you could iteratively simplify the input string until no more parentheses can be removed.
Below snippet is an implementation of that. The user's input is validated in real time:
For parsing an expression, use the Shunting yard algorithm, possibly with some extensions to support functions and more. See for instance my implementation here.