作者darkk6 (Mr. Pan)
看板Python
标题Re: [问题] 正规表示法"*?"
时间Mon Jun 6 12:13:59 2016
※ 引述《canamvskid (覚醒図监)》之铭言:
: 想请问一下,我用s1 = 'abc',然後 re.findall(r'o*?', s1)
: 得到的结果是 ['', '', '', '']
: 如果是从左到右一个个比对的话不是只有3个吗?
: 为什麽最後会多一个出来呢?
我对 Python 运作还不是很了解,但我猜这个和 Python 的 re 的运作方式有关
还有就是 string 的 slicing。
执行底下 Code :
import re
ptn='o*?'
sub='fooood'
p=re.compile(ptn)
iterator = p.finditer(sub);
for match in iterator:
print sub[match.start():match.end()] , match.span()
你会发现他运作的时候会抓出来的范围是
0:0 ==> "fooood"[0:0] = ''
1:1 ==> "fooood"[1:1] = ''
2:2 ==> "fooood"[2:2] = ''
3:3 ==> "fooood"[3:3] = ''
4:4 ==> "fooood"[4:4] = ''
5:5 ==> "fooood"[5:5] = ''
6:6 ==> "fooood"[6:6] = ''
如果按照这个方式来看:
+---+---+---+---+---+---+
| f | o | o | o | o | d |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
因为尽量少取的缘故,所以取出来的范围没有增加,
所以会 0:0 => 1:1 => 2:2 ....
应该是可以解释为何会多一个了吧
参考:
One way to remember how slices work is to think of the indices as
pointing between characters
https://docs.python.org/3/tutorial/introduction.html
在 3.1.2 Strings , 接近 3.1.3 Lists 的地方
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 49.159.236.36
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1465186442.A.13A.html
※ 编辑: darkk6 (49.159.236.36), 06/06/2016 13:04:15