且构网

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

如何在python regex中获取可能从字符串中相同位置开始的所有重叠匹配项?

更新时间:2023-02-21 15:56:02

Regex 在这里不是合适的工具,我建议:

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

  • 识别输入字符串中第一个字母的所有索引
  • 识别输入字符串中第二个字母的所有索引
  • 根据这些索引构建所有子字符串

代码:

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)

输出:

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