Re: [問題] 字串處理 - 簡化程式碼

看板Python作者 (1493)時間10年前 (2014/02/25 01:28), 編輯推噓4(407)
留言11則, 5人參與, 最新討論串2/3 (看更多)
# 剛好最近在用 # 針對您的items = '127.0.0.1:443;SSL'這個例子的簡單範例: import re match = re.search(u''' (?P<ip>[\d]+\.[\d]+\.[\d]+\.[\d]+)? : (?P<port>[\d]+)? ; (?P<comment>[\S]+)? ''', items, re.X) if match: ip, port, comment = match.group('ip'), match.group('port'), match.group('comment') ※ 引述《zha0 (這個帳號是掛網用)》之銘言: : 還是一樣又用 C 的方式在寫程式了 Q_q : 輸入的資料 : print "\t# {IP} : {PORT} ; {COMMENT}" : print "\tIP:Port1,Port2.....;Comment" : print "\tIP1-IP2:Port1;Comment" : print "\tIP/24:Port1\n" : print "\tIP;Comment" : 處理的程式片段 : items = '127.0.0.1:443;SSL' : ip = '' : port = '' : ipp = '' : comm = '' : if items.find(';'): : ipp, comm = items.split(';') : if ipp == '': : ipp = options.insert : if ipp.find(':'): : ip, port = ipp.split(':') : if ip == '': : ip = options.insert : print ip, port, comm : 請問如何將上面的程式碼, 寫的好看一點, 感覺一直 if 判斷, 好像沒 python 的味道 ~"~ : split 可以給了個字元 : ; 然後他就幫你自己切好嗎 ? 好像先從 : 切會比從 ; 切好 ?___? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 180.176.100.141 ※ 編輯: auoauo 來自: 180.176.100.141 (02/25 01:30) ※ 編輯: auoauo 來自: 180.176.100.141 (02/25 01:30)

02/25 02:17, , 1F
[\d] 可以寫 \d 就好啊XD
02/25 02:17, 1F

02/25 09:05, , 2F
除了用 re.X 之外,也可以多行字串合在一起。Ex
02/25 09:05, 2F

02/25 09:06, , 3F
"(?P<ip>\d+.\d+.\d+.\d+" # IP address
02/25 09:06, 3F

02/25 09:07, , 4F
"(?P<port>\d+)" # 有需要註解的話
02/25 09:07, 4F

02/25 09:08, , 5F
沒逗號的 ("..." "...") 會自動合併成一個字串
02/25 09:08, 5F

02/27 00:59, , 6F
喔喔樓上感謝, 忘了還能利用這樣來註解
02/27 00:59, 6F

02/27 11:00, , 7F
Thanks sharing!
02/27 11:00, 7F

03/04 19:18, , 8F
覺得 Regex 很複雜,我都喜歡用 split 耶.
03/04 19:18, 8F

03/04 19:18, , 9F
ip_port, comm = items.split(';')
03/04 19:18, 9F

03/04 19:18, , 10F
ip, port = ip_port.split(':')
03/04 19:18, 10F

03/04 19:19, , 11F
不過如果 port 不存在就有 valueError,我就抓exception
03/04 19:19, 11F
文章代碼(AID): #1J2u4Xi2 (Python)
文章代碼(AID): #1J2u4Xi2 (Python)