4

I want to write a python code generator, and it would be helpful if I had the regular expression that describes all valid python programs.

Does such a regular expression exist? What is it?

2
  • 3
    A regular expression? WHY? What are you trying to accomplish with that? It sounds like a truly awful idea, and most probably impossible. Commented Jul 3, 2012 at 6:08
  • As others have said, regular expressions are not sufficient to describes python syntax. However, the relatively short grammar that describes them can be seen in the source code here hg.python.org/cpython/file/d7bed032520b/Grammar/Grammar Commented Jul 3, 2012 at 8:10

3 Answers 3

11

Such a regular expression cannot exist, because regular expressions are, by definition, not powerful enough to recognize Turing complete languages (such as python).

Sign up to request clarification or add additional context in comments.

1 Comment

My + 1. For example, regular expressions cannot be used to accept the nested pair structures -- like nested parentheses in expressions.
5

If you generate a string with fragment of a Python code, and you want to check whether it is syntactically correct, try the built-in function compile. It returns the resulting code object or it raises the SyntaxError exception.

Comments

3

You'll want to lint your code. There are a couple of tools to do that with Python; pylint, PyChecker and pyflakes should all do the trick.

To answer your actual question: no, this is not a job for regular expressions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.