简体   繁体   English

如何在python3中将复杂的正则表达式写为字符串?

[英]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.

相关问题 如何使用 Python3(使用正则表达式)以字节为单位找到十六进制字符串的大小 - How do I find the size of a hex string in bytes using Python3 (with regex) 如何将复杂的字符串转换为python3中的列表? - How to convert a complex string to list in python3? 如何编写相关的REGEX模式以在python中提取较大文本字符串的子字符串 - How do I write a relevant REGEX pattern to extract sub-string of a larger text string in python 我如何 .decode(&#39;string-escape&#39;) 在 Python3 中? - how do I .decode('string-escape') in Python3? 如何在Python3中获取PyObject的字符串表示? - How do I get string representation of PyObject in Python3? 如何在 Python 中编写正则表达式以删除字符串中间数字的前导零 - How do I write a Regex in Python to remove leading zeros for a number in the middle of a string 如何使用正则表达式在python中进行复杂的替换? - how to do a complex replace in python using regex? 我如何编写 urilify 字符串 python - How do I write urilify string python 我将如何编写这个用 Python 2 编写的 for 循环,称为 python3 的语法中的字符串插值? - How would I write this for loop written in Python 2 known as string interpolation into syntax for python3? Python3正则表达式字符串格式 - Python3 regex string formatting
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM