且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我的正则表达式模式在 Python 中查找重复循环有什么问题?

更新时间:2023-01-19 16:15:48

添加 r 前缀:

r"([0-9]+?)\1+"

这将使反斜杠成为文字反斜杠而不是转义 1.

I want to match any string that has a recurring cycle. Like in this data:

3333333333333333333333333333333333333333 / 1 digit cycle(3)
1666666666666666666666666666666666666666 / 1 digit cycle(6)
1428571428571428571428571428571428571428 / 6 digit cycle(142857)
1111111111111111111111111111111111111111 / 1 digit cycle(1)
0909090909090909090909090909090909090909 / 2 digit cycle(09)
0834522467546323545411673445234655345222 / no cycle
0769230769230769230769230769230769230769 / 6 digit cycle(769230)
0714285714285714285714285714285714285714 / 6 digit cycle(714285)
0666666666666666666666666666666666666666 / 1 digit cycle(6)

The pattern I have tried is "([0-9]+?)\1+" which works well in other languages (like VB or text editors). I have stored these strings inside a list named values. So here is my code:

import re

#stuff to get values
pattern = re.compile("([0-9]+?)\1+")
for value in values:
    matchObj = pattern.search(value)
    print(matchObj) #-> None
    matchObj = pattern.findall(value)
    print(matchObj) #-> []

What am I doing wrong? Any hint is appreciated.

Add an r prefix:

r"([0-9]+?)\1+"

That will make the backslash a literal backslash instead of escaping the 1.