[問題] re 用法上的差異

看板Python作者 (Jimmy)時間5年前 (2019/04/16 14:45), 5年前編輯推噓3(304)
留言7則, 3人參與, 5年前最新討論串1/1
大家好,小弟今天在使用re尋找文章字串時,發現一個問題, 我想要從一個字串當中 找出 今天天氣好像(很好or不大好) 以下是程式碼: import re pattern=re.compile(r'今天天氣+.+(很好|不大好)') print(pattern.findall('今天天氣好像不是很好')) # [今天天氣好像不是很好] print(pattern.search('今天天氣好像不是很好')) # <re.Match object; span=(0, 10), match='今天天氣好像不是很好'> print(pattern.search('今天天氣好像不是很好').group()) # 今天天氣好像不是很好 print(pattern.findall('今天天氣好像很好')) # 今天天氣好像很好 print(pattern.search('今天天氣好像很好')) # <re.Match object; span=(0, 10), match='今天天氣好像很好'> print(pattern.search('今天天氣好像很好').group()) # 今天天氣好像很好 註解內容為我預期的輸出結果,而下列為輸出結果 ['很好'] <re.Match object; span=(0, 10), match='今天天氣好像不是很好'> 今天天氣好像不是很好 ['很好'] <re.Match object; span=(0, 8), match='今天天氣好像很好'> 今天天氣好像很好 想問一下,為什麼我用findall時只會回傳['很好'], 我的pattern裡面並沒有單獨這個條件呀QQ 若我的寫法有誤,我該怎麼修正? 感謝各位大神 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.136.42.144 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1555397137.A.1FF.html ※ 編輯: pig98520 (220.136.42.144), 04/16/2019 14:48:32

04/16 15:25, 5年前 , 1F
你用 () 代表想要找那東西,如果只是想要 group 改用
04/16 15:25, 1F

04/16 15:25, 5年前 , 2F
(?: ... )
04/16 15:25, 2F
※ 編輯: pig98520 (220.136.42.144), 04/16/2019 15:52:22

04/16 15:57, 5年前 , 3F
感謝樓上大大解惑,不過想問一下?: 有點看不大懂估狗到的
04/16 15:57, 3F

04/16 16:27, 5年前 , 4F
non capturing group, 只match但不捕捉結果
04/16 16:27, 4F

04/16 22:28, 5年前 , 5F

04/16 22:29, 5年前 , 6F
所有 Python 支援的規則都放在這裡了
04/16 22:29, 6F

04/16 22:38, 5年前 , 7F
感謝!
04/16 22:38, 7F
文章代碼(AID): #1SjNeH7_ (Python)