开发者

Python Math Regex [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist

Closed 9 years ago.

开发者_如何学Python Improve this question

I am creating a programming language in Python and one main component that I'm missing for the basic language is the ability to parse mathematical equations. I have the function to parse the math but I need to be able to check if the input is a math equation. I'm looking for a regex to match something like 3*x^(4*y)+1-(7*y*z/x).


You can't do what you want with regular expressions, it isn't a regular language. Python has extensions that you could abuse to do what you want but it would be un-maintainable and would not gain you anything over using a parser.

What you want is a Parser, a great easy to use library for Python is called pyparsing.

Here is a related answer with a pyparsing example.


You need to use an actual expression parser. Here is a question about expression parsing in Python:

Math Expression Evaluation

And here is the link from the best answer:

http://effbot.org/zone/simple-top-down-parsing.htm


I'm looking for a regex to match something like 3*x^(4*y)+1-(7*y*z/x).

You can't have a regular expression that matches strings such as "3*x^(4*y)...". The languages of well-balanced parenthesis is simply not regular.

(Actually, when talking about Python specific regular expressions, the above is a lie. Still though, I would claim that regular expressions would be the wrong tool for this task.)

I have the function to parse the math...

If you have a parser, I suggest you simply attempt to parse it, and say true if it succeeds, and false otherwise.


For parsing math text, reverse polish notation is often used. If you get your input in this syntax, then you can use a RPN python function to read it.

For a RPN parser in python, either this or this looks promising.

If your are writing your own programming language, you can simply force the user to use this notation, and check if it is not in RPN :)


It turns out I can use a recursive function that recognizes letters and numbers and then when parsing expressions, say for example "x+y", it checks whether "x" and "y" are valid math. So whenever you are validating an expression, if it is a letter or a number it is valid or if it is an operator with valid stuff on either side.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜