and the website (和网站)
I'm assuming you created your regex using one of the websites like regex101, right? (我假设您使用像regex101这样的网站之一创建了regex,对吗?)
If you look closely, regex101, it hints it uses raw strings. (如果仔细观察一下regex101,它暗示它使用的是原始字符串。)
In your case: (在您的情况下:)
pattern = re.compile("^0b(1*)(0*)(12)*(1)?$")
Python tries to interpret \1
as normal escape sequences - like \n
etc. (Python尝试将\1
解释为正常的转义序列-如\n
等。)
What you need, is \
that after string parsing, regex parser can parse. (您需要的是\
,在字符串解析后,正则表达式解析器可以解析。)
This means, escaping the backslash - \\
or using a raw string, so that Python knows it shouldn't parse any \n
s and similar ones. (这意味着,转义反斜杠- \\
或使用原始字符串,以便Python知道它不应解析任何\n
和类似的\n
。)
pattern = re.compile(r"^0b(1*)(0*)(12)*(1)?$")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…