如何在python regex中获取可能从字符串中相同位置开始的所有重叠匹配项? [英] How to get all overlapping matches in python regex that may start at the same location in a string?
本文介绍了如何在python regex中获取可能从字符串中相同位置开始的所有重叠匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在具有多个起点和终点的 Python 字符串中获取所有可能的重叠匹配项.
How do I get all possible overlapping matches in a string in Python with multiple starting and ending points.
我尝试使用正则表达式模块,而不是默认的 re 模块来引入重叠 = True 参数,但仍然缺少一些匹配项.
I've tried using regex module, instead of default re module to introduce overlapped = True argument, but still it is missing some matches.
尝试通过更简单的说明来描述我的问题:
Trying to describe my problem via a simpler illustration:
在以 a
开头并以 b
尝试了以下代码:
import regex
print(regex.findall(r'a\w+b','axaybzb', overlapped=False))
['axaybzb']
print(regex.findall(r'a\w+?b','axaybzb', overlapped=False))
['axayb']
print(regex.findall(r'a\w+b','axaybzb', overlapped=True))
['axaybzb', 'aybzb']
print(regex.findall(r'a\w+?b','axaybzb', overlapped=True))
['axayb', 'ayb']
预期输出为
['axayb', 'axaybzb', 'ayb', 'aybzb']
推荐答案
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']
这篇关于如何在python regex中获取可能从字符串中相同位置开始的所有重叠匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文