一. re模块是python中内置的用来支持正则表达式的模块
二.正则表达式的运用
match() 参数:1.正则表达式2.要进行查找的大字符串
match() 如果找到结果,返回对象结果,没有找到返回None
match() 要查找的子串必须位于大字符串中的开头位置才可以匹配成功,如果不在匹配失败,返回None
3. search()函数
search() 参数:1.正则表达式2.要进行查找的大字符串
search() 如果找到结果,返回对象结果,没有找到返回None
search() 要查找的子串可以位于大字符串中的任意位置,如果不在匹配失败,返回None
二.正则表达式的运用
1.准备正则
string = 'hello world'
pattern = re.compile('world')
2.使用正则表达式,从大字符串中搜索符合正则的字符串
match() 参数:1.正则表达式2.要进行查找的大字符串
match() 如果找到结果,返回对象结果,没有找到返回None
match() 要查找的子串必须位于大字符串中的开头位置才可以匹配成功,如果不在匹配失败,返回None
group()用来获取分组信息,分组信息在compile()正则表达式中设置
res = re.match(pattern, string)
print(res)
if res:
# group()用来获取分组信息,分组信息在compile()正则表达式中设置
print(res.group())
else:
print('没有匹配到数据')
3. search()函数
search() 参数:1.正则表达式2.要进行查找的大字符串
search() 如果找到结果,返回对象结果,没有找到返回None
search() 要查找的子串可以位于大字符串中的任意位置,如果不在匹配失败,返回None
res = re.search(pattern, string)
print(res)
if res:
print(res.group())
4.贪婪模式
. 匹配任意字符 *匹配前一个字符0次或无限次
默认 .*是贪婪模式 尽可能多的匹配数据
string2 = 'abcccbccbdebf'
pattern = re.compile('a.*b')
res = re.search(pattern, string2)
if res:
print(res.group())
else:
print('没有匹配到数据')
5.非贪婪模式
一般使用的都是非贪婪模式,尽可能少的去做数据的匹配
.*? 非贪婪模式pattern = re.compile('a.*?b')
res = re.search(pattern, string2)
if res:
print(res.group())
else:
print('没有匹配到数据')
.+? +表示匹配前一个字符1次或无限次 .+? 非贪婪模式
pattern = re.compile('a.+?b')
# pattern = re.compile('a.+b')
res = re.search(pattern, string2)
if res:
# 结果:abcccb
print(res.group())
else:
print('没有匹配到数据')
pattern = re.compile('a.*?b|c.*?b')
res = re.search(pattern, string2)
if res:
print(res.group())
else:
print('没有匹配到数据')
完整代码:
# -*- coding:utf-8 -*-
# re模块是python中内置的用来支持正则表达式的模块
import re
'''
'''
string = 'hello world'
# 1.准备正则
pattern = re.compile('world')
# 2.使用正则表达式,从大字符串中搜索符合正则的字符串
# match() 参数:1.正则表达式2.要进行查找的大字符串
# match() 如果找到结果,返回对象结果,没有找到返回None
# match() 要查找的子串必须位于大字符串中的开头位置才可以匹配成功,如果不在匹配失败,返回None
res = re.match(pattern, string)
print(res)
if res:
# group()用来获取分组信息,分组信息在compile()正则表达式中设置
print(res.group())
else:
print('没有匹配到数据')
# search() 参数:1.正则表达式2.要进行查找的大字符串
# search() 如果找到结果,返回对象结果,没有找到返回None
# search() 要查找的子串可以位于大字符串中的任意位置,如果不在匹配失败,返回None
res = re.search(pattern, string)
print(res)
if res:
print(res.group())
string2 = 'abcccbccbdebf'
# .匹配任意字符 *匹配前一个字符0次或无限次
# 默认 .*是贪婪模式 尽可能多的匹配数据
pattern = re.compile('a.*b')
res = re.search(pattern, string2)
if res:
print(res.group())
else:
print('没有匹配到数据')
# 一般使用的都是非贪婪模式,尽可能少的去做数据的匹配
# .*? 非贪婪模式
pattern = re.compile('a.*?b')
res = re.search(pattern, string2)
if res:
print(res.group())
else:
print('没有匹配到数据')
# .+? +表示匹配前一个字符1次或无限次 .+? 非贪婪模式
pattern = re.compile('a.+?b')
# pattern = re.compile('a.+b')
res = re.search(pattern, string2)
if res:
# 结果:abcccb
print(res.group())
else:
print('没有匹配到数据')
pattern = re.compile('a.*?b|c.*?b')
res = re.search(pattern, string2)
if res:
print(res.group())
else:
print('没有匹配到数据')
运行结果: