开发者

Matching unary signs and parsing math with Regex

开发者 https://www.devze.com 2023-03-16 20:39 出处:网络
One last Regex problem I need help with. What I am trying to do is be able to parse a math expression, while still having my Regex recognize unary symbols. I am using the followin开发者_如何学JAVAg to

One last Regex problem I need help with. What I am trying to do is be able to parse a math expression, while still having my Regex recognize unary symbols. I am using the followin开发者_如何学JAVAg to parse an integer:

[\+\-]?[0-9]+

Which works fine in these 2 scenarios:

myVar = -5
myVar = +5

Regex correctly identifies both -5 and +5 as integers. My problem is if I have a scenario like this:

myVar = 7-5

This, however, gets matched correctly:

myVar = 7*-5

Now what Regex is doing in the 7-5 scenario is its identifying 2 integers, 7 and -5. In reality, what I want is for it to be able to identify an integer (7), a minus sign (-) and then another integer (5). What Regex pattern do I need to do this?

Thanks in advance. This is .NET Regex, by the way.


Regex isn't the best choice for parsing math expressions. Look at Recursive descent parser or Reverse Polish notation or other more appropriate algorithm.


Assuming the problem input is limited as follows:

  1. A max of 1 binary operator (*, /, +, -)
  2. A max of 2 unary operators (+, -)
  3. All numbers are integers
  4. No whitespace

Then the following regular expression will work:
(([\+\-]?[\d]+)([\+\-\*\/]))*([\+\-]?[\d]+)
(Ignore the first group of results.)

If you want to consider spaces, add \s* between the parentheticals:
(([\+\-]?[\d]+)\s*([\+\-\*\/]))*\s*([\+\-]?[\d]+)

Example input and output (from groups 2-4):
Input \2 \3 \4 -5 -5 +5 +5 7-5 7 - 5 7*-5 7 * -5 -7*-5 -7 * -5


Use this:

  ((\d)+[\+\-\*/])*

Then use MatchCollection and Groups to get to the desired result.

0

精彩评论

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