# Author : XueFeng
# 动态模糊匹配
# 常用正则表达式符号
# '.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
# '^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a", "\nabc\neee", flags = re.MULTILINE)
# '$' 匹配字符结尾,或e.search("foo$", "bfoo\nsdfsf", flags = re.MULTILINE).group()也可以
# '*' 匹配*号前的字符0次或多次,re.findall("ab*", "cabb3abcbbac")结果为['abb', 'ab', 'a']
# '+' 匹配前一个字符1次或多次,re.findall("ab+", "ab+cd+abb+bba") 结果为['ab', 'abb']
# '?' 匹配前一个字符1次或0次
# '{m}' 匹配前一个字符m次
# '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}", "abb abc abbcbbb") 结果为['abb', 'ab', 'abb']
# '|' 匹配|左或|右的字符,re.search("abc|ABC", "ABCBabcCD").group() 结果 'ABC'
# '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
# '\A' 只从字符开头匹配,re.search("\Aabc", "Jimabc") 是匹配不到的
# '\Z' 匹配字符结尾,同$符
# '\d' 匹配数字0到9
# '\D' 匹配非数字
# '\w' 匹配[A-Z a-z 0-9]
# '\W' 匹配非[A-Z a-z 0-9]
# '\s' 匹配空白字符、\t、\n、\r,re.search("\s+", "ab\tc1\n3").group() 结果 '\t'
import re
# 从开头进行查找
print(re.match("^abc\d+", "abc123dasd"))
# 查找所有,但是只返回一次
print(re.search("a[a-zA-Z]+d", "abc123dasHd123fadf"))
print(re.search("#.+#", "abc123#dasHd12#3fadf"))
print(re.search("b", "abc123#dasHd12#3fadf"))
print(re.search("adb?", "adbc123#dasHd12#3fadf"))
print(re.search("(abc){2}(\|=){2}", "djhfkjsabcfahjifoabcabc|=|=sdji").group())
print(re.search("\A[1-9]+[a-z]+[a-z]\Z", "123djhfkjsabcfahjifoabcabcsdji").group())
print(re.search("\D+", "123djh \n\t-+|234asfd"))
print(re.search("\w+", "123djh \n\t-+|234asfd"))
print(re.search("\W+", "123djh \n\t-+|234asfd"))
print(re.search("\s+", "123djh \r\n -+|234asfd"))
print(re.search("(?P<id>[0-9]+)", "123dj234asfd").group())
print(re.search("(?P<id>[0-9]+)", "as123dj234asfd").groupdict())
print(re.search("(?P<id>[0-9]+)(?P<name>[a-zA-Z]+)", "as123dj234asfd").groupdict())
a = re.search("(?P<id>[0-9]+)(?P<name>[a-zA-Z]+)", "as123dj234asfd").groupdict()
print(a['id'])
a = re.search("(?P<id>[0-9]+)(?P<name>[a-zA-Z]+)", "as123dj234asfd").group('id')
print(a)
# 返回所有查找到的对象,以列表返回
print(re.findall("[0-9]{1,3}", "adbc123#dasHd12#3fadf"))
print(re.findall("ad|da", "adbc123#dasHd12#3fadf"))
# 分割
print(re.split("[0-9]+", "asd3df23fg877dfsi"))
# 替换
print(re.sub("[0-9]+", "|", "sd2fg3dfg432lop", count=2))
# 匹配反斜杠
print(re.search(r"\\[a-z]+", "12\dsd"))
print(re.search("\\\\[a-z]+", "12\dsd"))
# 匹配模式
# re.I(re.IGNORECASE): # 忽略大小写(括号内是完整写法)
# re.M(re.MULTILINE): # 多行模式,改变"^"和"$"的行为(括号内是完整写法)
# re.S(re.DOTALL): # 点任意匹配模式,改变"."的行为(括号内是完整写法)
print(re.search("^[0-9].+d$", "12dsc\r\ndfsf\r\n123d"))
print(re.search("^[0-9].+d$", "12dsc\r\ndfsf\r\n123d", flags=re.M))
print(re.search(".+", "12dsc\r\ndfsf\r\n123d"))
print(re.search(".+", "12dsc\r\ndfsf\r\n123d", flags=re.S))
# 小案例,身份证
print(re.search("(?P<Province>[0-9]{2})(?P<city>[0-9]{4})(?P<Birthday>[0-9]{8})", "220721199310124219").groupdict())
python_正则化re详细解释
最新推荐文章于 2024-05-06 23:59:04 发布