Re: [問題] 正規表示法"*?"

作者: canamvskid (覚醒図鑑)   2016-06-06 02:26:03
: 這個其實更有趣了,單看 o*? , 代表的是 零個以上的 o 盡量少取
: 根據 re.findall 的特性,他會由左而右不重疊的取出來
: 如果以 o*? 來去對 fooood 做 findall ,我們由左而右來看,
: 黃色的就是目前正在檢查的:
: fooood , f 符合 "零個以上的 o" 嗎?
: => Yes, "零個 o" , 所以得到第一個 ''
: fooood , o 符合 "零個以上的 o" 嗎?
: => Yes, 符合零個 o , 因為是 "盡量少取"
: 所以得到第二個 ''
: fooood , o 符合 "零個以上的 o" 嗎?
: => Yes, 符合零個 o , 因為是 "盡量少取"
: 所以得到第三個 ''
: 依此類推,所以你會得到很多的個 ''
想請問一下,我用s1 = 'abc',然後 re.findall(r'o*?', s1)
得到的結果是 ['', '', '', '']
如果是從左到右一個個比對的話不是只有3個嗎?
為什麼最後會多一個出來呢?
作者: rlinlen (Lin_len)   2016-06-06 11:33:00
'' 屬於'abc'的子集,findall的*(match 0)就把他抓進來了試試看r'.*?'和r'.+?'會比較好懂
作者: LiloHuang (十年一刻)   2016-06-08 21:05:00
每個字元之前都會 match,包含字串結尾 $ 前面的位置Empty matches are included in the result unless theresult unless they touch the beginning of anothermatch. https://goo.gl/qcxoYj有興趣也可以玩一下 re.findall(r'o*?', s1, re.DEBUG)抓到的空白為標問號的位置 '?a?b?c?' 這樣應該比較清楚就像 re.findall(r'o*?', '') 回傳的不是 empty list更正 空字串 不是空白 XD

Links booklink

Contact Us: admin [ a t ] ucptt.com