Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3正则表达式-查找所有重叠匹配';字符串中的开始和结束索引_Python_Regex - Fatal编程技术网

Python3正则表达式-查找所有重叠匹配';字符串中的开始和结束索引

Python3正则表达式-查找所有重叠匹配';字符串中的开始和结束索引,python,regex,Python,Regex,这是我最初的做法: string = '1'*15 result = re.finditer(r'(?=11111)', string) # overlapped = True # Doesn't work for me for i in result: # python 3.5 print(i.start

这是我最初的做法:

string = '1'*15     
result = re.finditer(r'(?=11111)', string)      # overlapped = True   
                                                # Doesn't work for me 
for i in result:                                # python 3.5
   print(i.start(), i.end())
它查找所有重叠的匹配项,但无法获取右端索引。 输出:

1 <_sre.SRE_Match object; span=(0, 0), match=''>
2 <_sre.SRE_Match object; span=(1, 1), match=''>
3 <_sre.SRE_Match object; span=(2, 2), match=''>
4 <_sre.SRE_Match object; span=(3, 3), match=''>
(and so on..)
1
2.
3.
4.
(等等)
我的问题:
如何找到所有重叠的匹配项,并同时获得所有的开始和结束索引?

您遇到的问题与这样一个事实有关,即前瞻是一个不消耗(即添加到匹配结果中)任何文本的索引。这只是字符串中的一个位置。因此,所有匹配都在字符串中的同一位置开始和结束

您需要用一个(即
(?=(11111))
)括起前瞻模式,并访问组1的开始和结束(使用
i.start(1)
i.end(1)
):

请参见,其输出为

(0, 5)
(1, 6)
(2, 7)
(3, 8)
(4, 9)
(5, 10)
(6, 11)
(7, 12)
(8, 13)
(9, 14)
(10, 15)

您能否与此实现进行比较,看看其中的差异可能在哪里

match = re.finditer(r'111','test111 end111 and another 111')
for i in match:
    print(i.start(),i.end()

如果这不适用于您,请分享您的数据样本

为什么您必须在“i.start(1)”和“i.end(1)”中键入“1”?在我的头脑中,“i.start()”应该足够了,显然不行。您需要获得组1的值开始和结束位置
i.start()
=
i.start(0)
,整个比赛开始位置。匹配是一个空字符串,是字符串中的一个位置,但捕获组保留实际值。我甚至不必运行它来判断这不是我想要的。
match = re.finditer(r'111','test111 end111 and another 111')
for i in match:
    print(i.start(),i.end()