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

看板Python作者 (Mr. Pan)時間9年前發表 (2016/06/06 04:14), 9年前編輯推噓0(000)
留言0則, 0人參與, 最新討論串5/5 (看更多)
※ 引述《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://www.ptt.cc/bbs/Python/M.1465186442.A.13A.html ※ 編輯: darkk6 (49.159.236.36), 06/06/2016 13:04:15
文章代碼(AID): #1NLFYA4w (Python)
討論串 (同標題文章)
文章代碼(AID): #1NLFYA4w (Python)