How to get all overlapping matches in python regex that may start at the same location in a string?

前端 未结 2 1456
栀梦
栀梦 2020-12-20 00:06

How do I get all possible overlapping matches in a string in Python with multiple starting and ending points.

I\'ve tried using regex module, instead of default re m

2条回答
  •  旧时难觅i
    2020-12-20 00:39

    Regex are not the proper tool here, I would recommend:

    • Identify all the indexes of the first letter in the input string
    • Identify all the indexes of the second letter in the input string
    • Build all the substrings based on those indexes

    code:

    def find(str, ch):
        for i, ltr in enumerate(str):
            if ltr == ch:
                yield i
    
    s = "axaybzb"
    startChar = 'a'
    endChar = 'b'
    
    startCharList = list(find(s,startChar))
    endCharList = list(find(s,endChar))
    
    output = []
    for u in startCharList:
        for v in endCharList:
               if u <= v:
                   output.append(s[u:v+1])
    print(output)
    

    output:

    $ python substring.py 
    ['axayb', 'axaybzb', 'ayb', 'aybzb']
    

提交回复
热议问题