Python正则表达式如何返回几个位置?

问题描述

这是Make python re.sub look multiple times

的扩展
s = 'cucumber apple tomato'

def f(match):
    if match.group(2) not in ('apple',):
        return '%s (%s)' % (match.group(1),match.group(2))
    else:
        return match.group()

正则表达式引擎去检查“黄瓜苹果”,没有匹配项,因此它继续进行下去。但是为什么它会跳过苹果而去番茄呢?为什么不勾选“苹果番茄”?

因此,re.sub(r'([a-z])+\s+[a-z]+',f,s)返回不变的字符串,但是re.sub(r'([a-z])+\s+[a-z]+','cucumber apple apple tomato')返回'cucumber apple apple (tomato)'。 看起来像引擎检查“黄瓜苹果”和“苹果番茄”,而不是“黄瓜苹果”,“苹果苹果”,“苹果番茄”。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)