正则表达式解析步骤

Regex parsing in steps

假设我有以下字符串:

s = "once upon a time, there was once a person"

不使用 findall 获取字符串中的所有 onces:

>>> re.findall(r'\bonce\b', s)
['once', 'once']

有没有办法递增地使用 search,所以它只 returns 第一次出现然后递增输入字符串?

while (s):
    x = re.search(r'\bonce\b', s) # return 'once' and increment the string to s[4:]
    yield x

使用re.finditer()

for match in re.finditer(r'\bonce\b', s):
    yield match

或者您可以 return 迭代器而不是编写自己的循环。

return re.finditer(r'\bonce\b', s)