[英]How do I write a complex regex as string in python3?
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... 很难理解而不必添加更多的反斜杠来逃避反斜杠......
Yes, they are. 对,他们是。 Use a raw string. 使用原始字符串。
>>> re.compile(r'(?<!\\)(?:(\')|")(?(1)(\\\'|[^\'\r])+?\'|(\\"|[^\r"])+?")')
<_sre.SRE_Pattern object at 0x242aa60>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.