1

So, I've got this regex I would like to compile:

(?<!\\)(?:(')|")(?(1)(\\'|[^'\r])+?'|(\\"|[^\r"])+?")

It works fine. But because there are ' and " signs, I need to escape them. So I do:

re.compile('''(?<!\\)(?:(')|")(?(1)(\\'|[^'\r])+?'|(\\"|[^\r"])+?")''')

Which give me the 'unbalanced parenthesis' error. I also tried:

re.compile('(?<!\\)(?:(\')|")(?(1)(\\\'|[^\'\r])+?\'|(\\"|[^\r"])+?")')

Are all those backslashes confusing it, somehow? It's hard enough to understand without having to add more backslashes to escape the backslashes...

1 Answer 1

4

Yes, they are. Use a raw string.

>>> re.compile(r'(?<!\\)(?:(\')|")(?(1)(\\\'|[^\'\r])+?\'|(\\"|[^\r"])+?")')
<_sre.SRE_Pattern object at 0x242aa60>
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, that's what those little r's mean I've been seeing here and there. Thanks
It makes more sense to use a triple-quoted string (as in the original post) instead of escaping quote characters.
Sure, but the problem is not the quotes.

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.