3

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 Answer 1

5

Add an r prefix:

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

thx. works like a charm. Although I saw that r as prefix in the examples of docs.python.org/library/re.html, I couldn't find the explanation for this
@Rafael T - Be sure to also check out the: Python Regular Expression HOWTO
@RafaelT @NedBatchelder How to match all recurring substrings ? abababqweqweqwe -> aba, qwe ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.