Re: [问题] 字串处理 - 简化程式码

楼主: auoauo (1493)   2014-02-25 01:27:58
# 刚好最近在用
# 针对您的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 可以给了个字符 : ; 然后他就帮你自己切好吗 ? 好像先从 : 切会比从 ; 切好 ?___?
作者: darkgerm (黑骏)   2014-02-25 02:17:00
[\d] 可以写 \d 就好啊XD
作者: ccwang002 (亮)   2014-02-25 09:05:00
除了用 re.X 之外,也可以多行字串合在一起。Ex"(?P<ip>\d+.\d+.\d+.\d+" # IP address"(?P<port>\d+)" # 有需要注解的话没逗号的 ("..." "...") 会自动合并成一个字串
作者: pycontw (PyCon APAC 2014)   2014-02-27 00:59:00
喔喔楼上感谢, 忘了还能利用这样来注解
楼主: auoauo (1493)   2014-02-27 11:00:00
Thanks sharing!
作者: huggie (huggie)   2014-03-04 19:18:00
觉得 Regex 很复杂,我都喜欢用 split 耶.ip_port, comm = items.split(';')ip, port = ip_port.split(':')不过如果 port 不存在就有 valueError,我就抓exception

Links booklink

Contact Us: admin [ a t ] ucptt.com