What is wrong with my regex Pattern to find recurring cycles in Python?

為{幸葍}努か 提交于 2020-01-01 14:29:04

问题


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.


回答1:


Add an r prefix:

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

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



来源:https://stackoverflow.com/questions/8640840/what-is-wrong-with-my-regex-pattern-to-find-recurring-cycles-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!