正则表达式

import re

# python中正则表达式的讲课
print('---------------------------match-----------------------------')
# match : 尝试从字符串的第一位开始找,如果找到了则返回对应的位置,没有找到则直接None
print(re.match('www', 'www.baidu.com').span())
print(re.match('www', 'https://www.baidu.com'))

line = 'Cats are smarter than dogs'
mathcObj = re.match(r'(.*) are (.*) .*', line, re.M|re.I);
print(mathcObj)
print(mathcObj.group())
print(mathcObj.group(1))
print(mathcObj.group(2))

print('------------------------search-------------------------------')
# search: 在指定的字符串中查找
print(re.search('w', 'www.baidu.com').span()) # 在起始位置匹配
print(re.search('www', 'https://www.baidu.com').span()) # 不在起始位置匹配

print('-------------------------compile----------------------------------')
pattem = re.compile(r'\d+') # 匹配1个或多个数字
print(pattem.match('one12twothree34foue')) # 从第一位开始进行数字的匹配
print(pattem.match('one12twothree34foue', 3, 10).span())
print('-------------')
pattern = re.compile(r'([a-z]+)', re.I) # re.I : 忽略大小写
m = pattern.match('Hello World Wide Web')
print(m)

print('---------------------------findall---------------------------------------')
# findall 找指定字符串中所有满足规则的字符串
pattern = re.compile(r'\d+')
result1 = pattern.findall('baidu 123 google 456')
result2 = pattern.findall('run88oob123google456', 0, 10)
print(result1)
print(result2)

# 使用正则表达式匹配邮箱
str = """
postmaster@phptr.comnoreply@phptr.comadmin@phptr.comeng@phptr.comsales@phpth.com
"""
pattern = re.findall(r'(.*?.com)', str, re.I)
print(pattern)
posted @ 2021-01-14 08:54  hellowould  阅读(81)  评论(0编辑  收藏  举报