python非贪婪匹配格式,Python正则表达式中的非贪婪

I try to understand the non-greedy regex in python, but I don't understand why the following examples have this results:

print(re.search('a??b','aaab').group())

ab

print(re.search('a*?b','aaab').group())

aaab

I thought it would be 'b' for the first and 'ab' for the second.

Can anyone explain that?

解决方案

This happens because the matches you are asking match afterwards. If you try to follow how the matching for a??b happens from left to right you'll see something like this:

Try 0 a plus b vs aaab: no match (b != a)

Try 1 a plus b vs aaab : no match (ab != aa)

Try 0 a plus b vs aab: no match (b != a) (match position moved to the right by one)

Try 1 a plus b vs aab : no match (ab != aa)

Try 0 a plus b vs ab: no match (b != a) (match position moved to the right by one)

Try 1 a plus b vs ab : match (ab == ab)

Similarly for *?.

The fact is that the search function returns the leftmost match. Using ?? and *? changes only the behaviour to prefer the shortest leftmost match but it will not return a shorter match that starts at the right of an already found match.

Also note that the re module doesn't return overlapping matches, so even using findall or finditer you will not be able to find the two matches you are looking for.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值