Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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
Python 如何使用regexp查找重叠匹配?_Python_Regex_Overlapping - Fatal编程技术网

Python 如何使用regexp查找重叠匹配?

Python 如何使用regexp查找重叠匹配?,python,regex,overlapping,Python,Regex,Overlapping,由于\w\w表示两个字符,因此应使用“he”和“ll”。但是为什么“el”和“lo”不匹配正则表达式呢 >>> match = re.findall(r'\w\w', 'hello') >>> print match ['he', 'll'] 默认情况下,findall不会产生重叠匹配。但是,此表达式不适用于: >>> match1 = re.findall(r'el', 'hello') >>> print match1

由于\w\w表示两个字符,因此应使用“he”和“ll”。但是为什么“el”和“lo”不匹配正则表达式呢

>>> match = re.findall(r'\w\w', 'hello')
>>> print match
['he', 'll']

默认情况下,
findall
不会产生重叠匹配。但是,此表达式不适用于:

>>> match1 = re.findall(r'el', 'hello')
>>> print match1
['el']
>>>
这里的
(?=…)
是:

(?=…)
匹配下一个,但不使用任何 一串这称为前瞻断言。例如
Isaac(?=Asimov)
将匹配
'Isaac'
,前提是它后跟
'Asimov'


除了零长度断言外,输入中的字符将始终在匹配中使用。如果您想要再次捕获输入字符串中的某些字符,则需要在正则表达式中使用零长度断言

有几种零长度断言(例如,
^
(输入/行的开始)、
$
(输入/行的结束)、
\b
(字边界)),但要环顾四周(
(?!)
负面展望)在这里不是很有用:如果它们断言为true,则内部捕获失败;如果它们断言为false,则匹配失败。这些断言的长度为零(如前所述),这意味着它们将在不使用输入字符串中的字符的情况下进行断言。如果断言通过,它们将实际匹配空字符串

应用上述知识,适用于您案例的正则表达式将是:

>>> re.findall(r'(?=(\w\w))', 'hello')
['he', 'el', 'll', 'lo']
可以使用支持重叠匹配的

(?=(\w\w))

我不是正则表达式专家,但我想回答我的类似问题

如果要使用具有前瞻功能的捕获组:

示例正则表达式:
(\d)(?=。\1)

字符串:
5252

这将匹配前5个和前2个


(\d)
用于创建一个捕获组,
(?=\d\1)
用于匹配捕获组1后面的任何数字,而不使用字符串,因此允许重叠

,但我不明白如果它在正向前瞻断言中,为什么会前进到下一个字母。请解释一下,好吗?
>>> import regex as re
>>> match = re.findall(r'\w\w', 'hello', overlapped=True)
>>> print match
['he', 'el', 'll', 'lo']