参考:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
# re.match import re m = re.match(r'(w+) (?P<sign>.*)', 'hello standby!') print(type(m)) # <class '_sre.SRE_Match'> print(m) # <_sre.SRE_Match object; span=(0, 14), match='hello standby!'> print(m.groupdict()) # {'sign': 'standby!'} # re.search import re ret = re.search("(?P<arg_name>d+)","hello456liu999") print(ret) # <_sre.SRE_Match object; span=(5, 8), match='456'> li = ret.group("arg_name") print(type(li)) # <class 'str'> print(li) # 456
# re.match匹配ip地址 import re # 将正则表达式编译成Pattern对象 pattern = re.compile(r'(?<![.d])(?:d{1,3}.){3}d{1,3}(?![.d])') # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None ip_list = [ '1.1.1.1', 'asasas', '098121212121290808', '10.10.12.1', '188.12.23.4', ] for ip in ip_list: if pattern.match(ip): print(ip)