提前谢谢。我想找到K和N之间发生的所有子串,尽管K和N发生在任意次数之间。
例如
一个= 'KANNKAAN'
输出;
[KANNKAAN,KANN,KAN,KAAN]
答案 0 :(得分:2)
import re
def occurences(ch_searched, str_input):
return [i.start() for i in re.finditer(ch_searched, str_input)]
def betweeners(str_input, ch_from, ch_to):
starts = occurences(ch_from, str_input)
ends = occurences(ch_to, str_input)
result = []
for start in starts:
for end in ends:
if start<end:
result.append( str_input[start:end+1] )
return result
print betweeners('KANNKAAN', "K", "N")
这就是你需要的吗?
答案 1 :(得分:1)
另一种方式:
def findbetween(text, begin, end):
for match in re.findall(begin + '.*' +end, text):
yield match
for m in findbetween(match[1:], begin, end):
yield m
for m in findbetween(match[:-1], begin, end):
yield m
>>> list(findbetween('KANNKAAN', 'K', 'N'))
['KANNKAAN', 'KAAN', 'KANN', 'KAN']