[問題] regex 的 \1 抓不到字串已刪文

看板Python作者 (Neisseria)時間11年前 (2014/06/16 10:38), 編輯推噓1(102)
留言3則, 3人參與, 最新討論串1/1
小弟我重寫書上一個將字串相接的小程式 部分程式碼如下 http://pastebin.com/c4GUJ4UW 但目前錯誤未修正,僅供參考 原來的想法是將兩段字串相接起來,像是 字串1: merely players;\nThey have 字串2: They have their exits and their entrances,\n 相接的方式為 "".join([字串1, 'XXX', 字串2]) 得到字串3 如下 merely players;\nThey haveXXXThey have their exits and their entrances,\n 然後用 regex 得到重疊的部分 match = re.match(r'([\S ]{2,})XXX\1', 字串3) if match: print match.group(1) 理論上應該輸出 "They have" 才是,卻一直 match 不到 我還刻意用 Perl 以同樣的 regex pattern 跑,可以抓得到 $1 (假設將字串3 用 print 輸出到 stdout) $ python file.py | perl -n -e 'print "$_$1\n" if /([\S ]{2,})XXX\1/;' 看來似乎也不是 pattern 的問題? 希望各位大大可以解惑,感恩 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.104.139.82 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1402886307.A.B6E.html

06/16 12:55, , 1F
不是用 match; read the doc http://d.pr/eqj6
06/16 12:55, 1F

06/16 17:49, , 2F
match 很嚴格的,換一個~
06/16 17:49, 2F

06/16 21:38, , 3F
看來我對於 Python 的 Regex 還得多學學~
06/16 21:38, 3F
文章代碼(AID): #1JdbYZjk (Python)
文章代碼(AID): #1JdbYZjk (Python)