Python - 正则进阶

# | 或 :匹配左右任意一个表达式

import re

# res = re.match('[1-9]?\d$|123', '123')  # [1-9]?\d$ 最多两个字符,但是或|运算,用了123去匹配
# print(res.group())  # 123

# res = re.match('[1-9]?\d$|\w*', '123youare')  # [1-9]?\d$ 最多两个字符,但是或|运算,用了\w*去匹配多个单词
# print(res.group())  # 123youare

# () 分组
# 139邮箱 11位手机号,并且第一位为1

# res = re.match('1\d{10}@139.com$', '12345678901@139.com')
# print(res.group())    # 12345678901@139.com

# res = re.match('\w{4,20}@(139|163|qq).com$', '12345678901@qq.com')
# print(res.group())  # 12345678901@qq.com


# 不以 4,7结尾的4位数字号码
#
# res =re.match('\d{3}[^47]')


# 提取座机号,区号
# res = re.match('\d{3}-\d{7}', '110-1234567aaaaa')
# print(res.group())

# res = re.match('(\d{3})-(\d{7})', '110-1234567aaaaa')
# print(res.group(0))   # 0 是全部匹配      110-1234567
# print(res.group(1))   # 1 是匹配第1个分组  110
# print(res.group(2))   # 2 是匹配第2个分组  1234567


# res = re.match('<[a-zA-Z]*>', '<html>hh<html>')
# print(res.group())      # <html>
# res = re.match('<[a-zA-Z]*>\w*<[a-zA-Z]*>', '<html>hh<html>')
# print(res.group())      # <html>hh<html>
# res = re.match('<[\D]*>', '<html>hh<html>')
# print(res.group())      # <html>hh<html>
# res = re.match('<(\w*)>\w*</\\1>', '<html>hh</html>')   # \1引用分组1的内容(\w*)
# print(res.group())      # <html>hh</html>

# 分组取别名 (?P<name>)
res = re.match("<(?P<n1>\w*)><(?P<n2>\w*)>.*</(?P=n2)></(?P=n1)>",
               "<html><h1>www.baidu.com</h1></html>"
)
print(res)
print(res.group())  # <html><h1>www.baidu.com</h1></html>







"""
search(): 扫描整个字符串,并返回第一次成功的匹配
"""


import re
# res = re.search("\d+", "今天是30号吗")
# print(res.group())  # 30



"""
findall(): 以列表形式返回匹配到的字符串(匹配所有)
"""

# res = re.findall("\d", '123')   # \d 是匹配单个数字
# print(res)      # ['1', '2', '3']
#
# res = re.findall("[^\d]","你在123456干什么啊")
# print(res)      # ['你', '在', '干', '什', '么', '啊']

"""
sub(): 将匹配到的数据进行替换

re.sub(pattern定义替换的格式,repl表示用什么内容来替换,string要被替换的字符串,count替换的次数,flags=0)
"""

# res = re.sub("\d", '12', '我看了50本书', 1)
# print(res)  # 我看了120本书
#
# res = re.sub("\d", '12', '我看了50本书', 2)
# print(res)  # 我看了1212本书
#
# res = re.sub("\d", '12', '我看了5本书', 1)
# print(res)     # 我看了12本书


"""
split(): 根据匹配进行切割字符串,并返回一个列表
split(pattern,string,maxsplit,flags=0)
"""
# res = re.split(';| ', 'a d;c d')
# print(res)      # ['a', 'd', 'c', 'd']

res = re.split(';| ', 'a d;c d', 2)
print(res)      # ['a', 'd', 'c d']




print("abc\n123")
# abc
# 123

print("abc\\n123")
# abc\n123


import re

res = re.match(r'\\', '\\dec')
print(res.group())



















"""
贪婪匹配: 匹配尽可能长的字符串,默认情况下,采用贪婪匹配;
非贪婪匹配:匹配尽可能少的字符串,使用?表示非贪婪匹配

"""

import re

# match
# res = re.match("ab*", "abbc")
# print(res.group())      # abb
#
#
# res1 = re.match("a*?", "aaa")
# print(res1.group())     # 什么都没有


# findall

str1 = '<h1>hello world </h1>'
res = re.findall('<.*>', str1)
print(res)  # ['<h1>hello world </h1>']

res = re.findall('<.*?>', str1)
print(res)  # ['<h1>', '</h1>']

  

posted @ 2021-04-26 22:26  每天都在学习的自己  阅读(73)  评论(0)    收藏  举报