[Python-ideas] PEP 8: raw strings & regular expressions

Chris Angelico rosuav at gmail.com
Mon Oct 26 22:26:23 EDT 2015


On Tue, Oct 27, 2015 at 8:44 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
> You seem to be seeking something else: a pattern that matches all valid
> regex patterns, *and* will never match any string that is not a valid
> regex pattern. The latter is rather more difficult.

"Rather more difficult" may be an understatement. A regex can contain
grouping parentheses which can arbitrarily nest, and matching that
with a regex is, AIUI, fundamentally impossible. So I don't think it's
possible to have a regex that validates a regex.

Fortunately, it's easy to write a function that validates a regex.

def is_regex(s):
    try: re.compile(s)
    except re.error: return False
    return True

ChrisA


More information about the Python-ideas mailing list