看板 Python 關於我們 聯絡資訊
: 這個其實更有趣了,單看 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個嗎? 為什麼最後會多一個出來呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.93.94 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1465151166.A.3F9.html
rlinlen: '' 屬於'abc'的子集,findall的*(match 0)就把他抓進來了 06/06 11:33
rlinlen: 試試看r'.*?'和r'.+?'會比較好懂 06/06 11:34
LiloHuang: 每個字元之前都會 match,包含字串結尾 $ 前面的位置 06/08 21:05
LiloHuang: Empty matches are included in the result unless the 06/08 21:05
LiloHuang: result unless they touch the beginning of another 06/08 21:05
LiloHuang: match. https://goo.gl/qcxoYj 06/08 21:06
LiloHuang: 有興趣也可以玩一下 re.findall(r'o*?', s1, re.DEBUG) 06/08 21:07
LiloHuang: 抓到的空白為標問號的位置 '?a?b?c?' 這樣應該比較清楚 06/08 21:15
LiloHuang: 就像 re.findall(r'o*?', '') 回傳的不是 empty list 06/08 21:16
LiloHuang: 更正 空字串 不是空白 XD 06/08 21:20