[英]Python: Extract substring that matches regular expression in a string
[英]Finding a given substring in a string with Regular Expression in Python
import re
S = 'aaadaa'
matches = re.finditer('(aa)', S)
if matches:
#print(matches)
for match in matches:
print(match)
else:
print("No match")
当前输出为:
<re.Match object; span=(0, 2), match='aa'>
<re.Match object; span=(4, 6), match='aa'>
但我希望它应该给出以下值:
<re.Match object; span=(0, 2), match='aa'>
<re.Match object; span=(1, 3), match='aa'>
<re.Match object; span=(4, 6), match='aa'>
有人可以帮我吗?
摘自我在评论中链接的答案,这是您需要的模式: (?=(aa))
。
你必须访问匹配使用子match_obj.groups(1)
并使用匹配指标match_obj.span(1)
这里的问题是,一旦re
模块匹配双aa
,它也会消耗这两个字母。 但是,您想要重叠匹配。 您可以在这里使用的一个技巧是搜索a(?=a)
:
S = 'aaadaa'
matches = re.findall(r'a(?=a)', S)
matches = [s + "a" for s in matches]
print(matches)
['aa', 'aa', 'aa']
请注意,我们将第二个a
标记到输出列表,因为在每一步实际上只匹配第一个字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.