开发者

Regular Expression for Simple Arithmetic String

I'm trying to validate a simple ar开发者_开发问答ithmetic expression to insure it fits within the format operand operator operand : 234.34 + 5. I figured out how to validate this easy enough, but I want the users to be able to continue inputting more than 2 values such as: 234.34 + 5 / 6 * 7 - -34. So far my regex is as follows:

[-]*\d+[.\d+[E\d+]*]*[\s+[*+/-]\s+[-]*\d+[.\d+[E\d+]*]*]*

This partially works, but the problem I have is it allows for some strange things I don't want such as -4.34.1 - 34 +

Any suggestions?


Try this. It's ugly as hell but it should work (if you aren't using any parentheses):

-?\d+(?:\.\d+(?:E\d+)?)?(\s*[-+/\*]\s+-?\d+(?:\.\d+(?:E\d+)?)?)+

Explanation

This will math a number followed by an operator and a number indefinitely

  • -?\d+(?:\.\d+(?:E\d+)?)? Match a number
  • (
    • \s* optional whitespace
    • [-+/\*] any operator: +, -, *, /
    • \s+ at least one whitespace (to avoid a --b)
    • -?\d+(?:\.\d+(?:E\d+)?)? match another number
  • )+ repeat this block one or more times

And the number expression:

  • -? optional -
  • \d+ digits (one or more)
  • (?: start of optional part
    • \. dot
    • \d+ digits
    • (?: start of optional scientific notation part
      • E match E char
      • \d+ match digitx
    • )? close of the optional scientific notatotion part
  • )? close optional group

But i strongly suggest trying to write a proper parser for this, it will also allow supporting of parentheses: a + (b + c).


I hate to be "that guy" but why not just write a simple validator that parses the string without using regular expressions? What's the reasoning behind using regular expressions for this? If you were to write your own parser, not only will the solution be easier to understand and maintain but with a little bit more work you would be able to evaluate the expression as well.


It may be best to just write a parser. I know, that sounds scary, but this is actually a second-year homework exercise at college.

See Dijkstra's Shunting-yard algorithm. This will allow you to both verify and evaluate the expression, so if that is where you're going with this project, you're going to have to implement it anyways...


i released an expression evaluator based on Dijkstra's Shunting Yard algorithm, under the terms of the Apache License 2.0:

http://projects.congrace.de/exp4j/index.html


Why not use string.split to get each operand and value by itself. Then you can parse it using much simpler regex ([\d*.\d*|\d|+|-|*|/]) or just Integer.getInterger for your values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜