Finding the recurring pattern

后端 未结 2 569
青春惊慌失措
青春惊慌失措 2021-01-13 11:21

Let\'s say I have a number with a recurring pattern, i.e. there exists a string of digits that repeat themselves in order to make the number in question. For example, such a

相关标签:
2条回答
  • 2021-01-13 11:35
    (.+?)\1+
    

    Try this. Grab the capture. See demo.

    import re
    p = re.compile(ur'(.+?)\1+')
    test_str = u"1234123412341234"
    
    re.findall(p, test_str)
    

    Add anchors and flag Multiline if you want the regex to fail on 12341234123123, which should return None.

    ^(.+?)\1+$
    

    See demo.

    0 讨论(0)
  • 2021-01-13 11:48

    One way to find a recurring pattern and number of times repeated is to use this pattern:

    (.+?)(?=\1+$|$)  
    

    w/ g option.
    It will return the repeated pattern and number of matches (times repeated)
    Non-repeated patterns (fails) will return only "1" match
    Repeated patterns will return 2 or more matches (number of times repeated).
    Demo

    0 讨论(0)
提交回复
热议问题