Python正则
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python正则相关的知识,希望对你有一定的参考价值。
# !/user/bin/python # -*- coding: utf-8 -*- import re # match, 从头开始匹配 a = re.match("192", "inet 地址:192.168.12.44") # 不匹配, 因为字符串开头不是192. b = re.match("inet", "inet 地址:192.168.12.44") # 返回<_sre.SRE_Match object; span=(0, 4), match=‘inet‘> print(a) print(b) print(b.group()) # 返回所有匹配的值. # 点代表除了\n 之外的任意字符 c = re.match(".+", "inet 地址:192.168.12.44") print(c) # /w需要至少匹配一次 d = re.match("/w?", "inet 地址:192.168.12.44") print(d) # ?代表匹配一次或零次 d = re.match("/w?", "inet 地址:192.168.12.44") print(d) # search 搜索; groups可对字符串中的字符分组 e = re.search("(abc){2}a(123|456)c", "abcabca456c") print(e.group()) # 返回abcabca456c print(e.groups()) # 返回(‘abc‘, ‘456‘) f = re.search("(\d\d)(\d\d)(\d){2}(\d){4}", "370218198709279908") print(f.groups()) # (\d\d) 的形式会把匹配的字符都连起来写; (\d){4}的形式会把最后一个字符单个写出来. # 返回(‘37‘, ‘02‘, ‘8‘, ‘7‘). h = re.search("(\d{2})(\d{2})(\d{2})(\d{4})(\d{4})", "370218198709279908") print(h.groups()) # 返回(‘37‘, ‘02‘, ‘18‘, ‘1987‘, ‘0927‘). 把字符串分组 # A 只从字符开头进行匹配 i = re.search("\Aa", "abcabca456c") print(i.group()) # 返回a # ^ 以指定字符/数字开头, 和A的作用一样 g = re.search("^37", "370218198709279908") print(g.group()) # 返回37 # # groupdict 以字典的形式返回匹配的字符串 # k = re.search("(?P<province>[0,9]{4})(?P<city>[0,9]{2})(?P<birthday>[0,9]{4})", "370218198709279908") # print(k.groupdict()) # TODO 为什么返回AttributeError: ‘NoneType‘ object has no attribute ‘groupdict‘,演示是在Xshell5环境 # # 搜索IP地址 # m = re.search("\d{1,3)\.\d{1,3}\.\d{1,3}\.\d{1,3}", "inet 地址:192.168.12.44") # TODO 为什么报错. 演示是在Xshell5环境 # print(m) # n = re.search("(\d{1,3)\.){3}", "inet 地址:192.168.12.44") # print(n) # findall o = re.findall("\d+","abcdfewage25435r3") print(o) #返回[‘25435‘, ‘3‘] p = re.findall("[a-zA-Z]+]", "abjvldAFEWdfh2894AJlfd89AHvhk") print(p) q = re.findall("\D+]", "abjvldAFEWdfh2894AJlfd89AHvhk") print(q) # sub 替换 r = re.sub("\d+","|","abjvldAFEWdfh2894AJlfd89AHvhk" ) # 将数字替换成| print(r) # 返回 abjvldAFEWdfh|AJlfd|AHvhk # split 拆分 s = re.split("\\\\", r‘c:\user\data\python35‘) print(s) # 返回 [‘c:‘, ‘user‘, ‘data‘, ‘python35‘]
以上是关于Python正则的主要内容,如果未能解决你的问题,请参考以下文章