❔ calculator
I want to write a function which returns if a string can be used as calculator input. The calculator should use the Operators +-*/, brackets and foats.
Should i use regex for this? How can I use it for this?
11 Replies
Do not use regex for this
I'm guessing your main problem is that you want to respect operator precedence
if a string can be used as calculator inputDo you want to actually perform a calculation or just check if the input is valid?
The theory behind it is called parsing in the very general sense, and for your case it has an even more precise formalisation called PEG (https://en.wikipedia.org/wiki/Parsing_expression_grammar)
But in case you are not a fan of theory, there are nice algos to deal with this, like Shunting-Yard (https://en.wikipedia.org/wiki/Shunting_yard_algorithm)
If you just want to verify the input, your case might be way simpler
Just check if ne input is valid
What are your requirements?
What you'll have to do is likely
1. check for characters other than whitespace, digits, and
.+-*/()
2. check if literals are formatted correctly (i.e. 1.2
is valid but 2..3
is not)
3. check that all brackets are paired properly (i.e. (1)
is valid but ((2)
is not)
4. check that no consecutive operators are present (i.e. 1+2
is valid but 2++3
is not)
Or you could write a parser but only use the errors it produces, although depends on how much work you're willing to put into this.
actually writing a parser might be easier since that would handle more cases ¯\_(ツ)_/¯Thanks, when should i use regex?
when you want to match a pattern
Regexes are powerful except when you need a lot of logic in your pattern.
For instance, I don't think checking bracket pairs would be very nice with regex.
Regex shines at finding substrings and unique occurrences of patterns in a string
I'd say the easiest here would be to tokenize your input, which already does a lot of the validation
After that, you'd check if tokens following eachother is legal, and count if parens are balanced
It's not quite parsing, you get to not write recursive expression parsing 😄
Thanks
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.