1.基本字符
1.1 行定位符
行定位符用来描述字符串的边界。以字符串’hello world’为例
^
表示行的开始
如^hello world 可以匹配到 ‘hello world xxxxxxxxxxxxx’。但匹配不到’xxxxxxxxxxxxx hello world’
$
表示行的结束
如hello world$ 可以匹配到’xxxxxxxxxxxxx hello world’。但匹配不到 ‘hello world xxxxxxxxxxxxx’
无行定位符则表示可以在任意部分匹配。
1.2 元字符
字符 | 功能 |
---|---|
. | 匹配除换行符外的任意字符 |
\w | 匹配字母、数字、下划线或汉字 |
\W | 匹配除字母、数字、下划线或汉字以外的字符 |
\s | 匹配任意空白字符 |
\S | 除单个空白字符(包括Tab键和换行符)以外的所有字符 |
\d | 匹配数字 |
\D | 任意非数字 |
\A | 从字符串开始处开始匹配 |
\Z | 从字符串结束处开始匹配 |
\b | 匹配一个单词的边界,单词的分解符通常是空格、标点符号或者换行 |
\B | 匹配非单词边界 |
^ | 匹配字符串的开始 |
$ | 匹配字符串的结束 |
() | 被括起来的表达式将作为分组 |
如果想用 点 符号匹配换行符,需要加入参数re.S.
1.3限定符
限定符 | 功能 | 示例 |
---|---|---|
? | 匹配前边的字符串0次或1次 | hello?world可以匹配hellworld和helloworld |
+ | 匹配前边的字符串1次或多次 | hello+world可以匹配helloworld到hellooooooo…world |
* | 匹配前边的字符串0次或1次或多次 | hello*world可以匹配hellworld和helloworld到helloooo…world |
{n} | 匹配前边的字符串n次 | hello{3}world可以匹配helloooworld |
{n,} | 匹配前边的字符串至少n次 | hello{3,}world可以匹配helloooworld到hellooooo…world |
{n,m} | 匹配前边的字符串至少n次,至多m次 | hello{3,10}world可以匹配helloooworld到hellooooooooooworld |
1.4字符类
[ ]
使用方括号[]
- [abcdef]表示匹配字母abcdef中的任意一个
- [a-z]表示匹配任意一个小写字母
- [A-Z]表示匹配任意一个大写字母
- [0-9]表示匹配任意一个数字
- 在只考虑英文的情况下,[a-z0-9A-z]则完全等同于\w
- 如果想匹配任意一个汉字,可以用[\u4e00-\u9fa5]
1.5排除字符
将^符号放在方括号中,表示排除的意思。
[^a-zA-Z]
该表达式用于匹配任何一个不是字母的字符
1.6选择字符
选择字符使用 | 符号来实现,可以理解为逻辑“或”
|
如 (^\d{18}$)|(^\d{17}(a|X|x))
此正则表达式表示匹配18位的数字,
或者前17位为数字且第18位为a、X或x 的18位字符
1.7转义字符
即同python中的转义字符 \ 符号。将特殊字符转化为普通字符。
\
1.8分组
即使用小括号 ( )。
()
2. 使用match()进行匹配
match()方法从字符串开始处进行匹配,匹配成功则返回Match对象,否则返回None。
re.match(pattern, string, [flags])
- pattern 模板字符串
- string 要匹配的字符串
- flags 可选参数,表示修饰符,用于控制匹配方式,
如设置为I(大写字母I)表示不区分字母大小写,
设为S表示使用 .(点)字符匹配所有字符,包括换行符,
import re
pattern = 'hello_\w+' # 表达式字符串
string = 'Hello_world' # 要匹配的字符串
match = re.match(pattern, string, re.I) # 匹配字符串,不区分大小写
print(match) # 输出匹配结果
string = 'abc Hello_world'
match = re.match(pattern, string, re.I) # 匹配字符串,不区分大小写
print(match)
程序运行结果:
匹配成功后打印出匹配的数据则使用 group() 方法。
result = re.match(pattern, s) # 查看s里面是否有pattern这个数据
# 如果匹配成功了,就打印匹配的数据
if result:
print(result.group())
else:
print('没有匹配到')
要获取匹配值的开始位置可以使用Match对象的start()方法
要获取匹配值的结束位置可以使用Match对象的end()方法
要获取匹配值匹配位置(开始位置和结束位置)的元组可以使用Match对象的span()方法
要获取匹配的字符串也可以用Match对象的string属性
import re
pattern = 'hello_\w+' # 模式字符串
string = 'HELLO_world' # 要匹配的字符串
match = re.match(pattern, string, re.I) # 匹配字符串,不区分大小写
print('匹配值的起始位置:', match.start())
print('匹配值的结束位置:', match.end())
print('匹配位置的元组:', match.span())
print('要匹配的字符串:', match.string)
print('匹配数据:', match.group())
程序运行结果:
上边是示例皆在匹配以指定字符串开头的字符串,下边匹配以任意字符串开头的字符串:
import re # 导入re模块
pattern = '.ello' # 表达式
match = re.match(pattern, 'hello') # 匹配字符串
print(match) # 打印匹配结果
match = re.match(pattern, 'aello') # 匹配字符串
print(match)
match = re.match(pattern, '6ello') # 匹配字符串
print(match)
match = re.match(pattern, 'ello') # 匹配字符串
print(match)
程序运行结果:
如果想匹配多个字符串:
import re # 导入re模块
pattern = 'hello|我' # 表达式,表示需要匹配“hello”或“我”开头的字符串
match = re.match(pattern, 'hello word') # 匹配字符串
print(match) # 打印匹配结果
match = re.match(pattern, '我爱Python') # 匹配字符串
print(match)
程序运行结果:
如果想要获取匹配的部分内容
import re # 导入re模块
# 表达式,“hello”开头,“\s”中间空格,“(\w+)”分组后面所有字母、数字以及下划线数据
pattern = 'hello\s(\w+)( abc)'
match = re.match(pattern, 'hello world abc') # 匹配字符串
print(match) # 打印匹配结果
print(match.group()) # 打印所有匹配内容
print(match.group(0))
print(match.group(1)) # 打印分组指定内容
print(match.group(2))
程序运行结果:
从中可以看出,group()方法默认参数为0,默认输出匹配的所有内容,如果参数为1,则输出第一个分组匹配到的部分,参数为2则输出第二个分组匹配到的部分,以此类推。(不同于一般的索引从0开始的规则)
匹配指定首位的字符串
import re # 导入re模块
# 表达式,h开头,n$表示n结尾
pattern = 'h\w+\s[\u4e00-\u9fa5]+\s\w+n$'
match = re.match(pattern, 'hello 我爱 Python') # 匹配字符串
print(match) # 打印匹配结果
print(match.group()) # 打印所有匹配内容
程序运行结果:
__
3.使用search()进行匹配
search()方法用于在整个字符串中搜索第一个匹配的值,如果在第一匹配位置匹配成功,则返回Match对象,否则返回None。
re.search(pattern, string, [flags])
- pattern 模板字符串
- string 要匹配的字符串
- flag 可选参数,修饰符
获取第一匹配值
import re
pattern = 'hello_\w+' # 模式字符串
string = 'HELLO_world' # 要匹配的字符串
match = re.search(pattern, string, re.I) # 搜索字符串,不区分大小写
print(match) # 输出匹配结果
string = 'abcHELLO_world'
match = re.search(pattern, string, re.I) # 搜索字符串,不区分大小写
print(match) # 输出匹配结果
程序运行结果:
可选匹配
(即针对有的部分可有可无的情况)
表达式’(\d?)+hello\s?([\u4e00-\u9fa5]?)+'分析:
?表示0次或1次,+表示一次或多次,?+在一起表示0次到任意次。
(\d?)+则表示多个数字可有可无,
\s?表示0个或1个空格,
([\u4e00-\u9fa5]?)+多个汉字可有可无
import re # 导入re模块
pattern = '(\d?)+hello\s?([\u4e00-\u9fa5]?)+'
match = re.search(pattern, '01hello')
print(match)
match = re.search(pattern, 'hello')
print(match)
match = re.search(pattern, 'hello ')
print(match)
match = re.search(pattern, 'hello 第一')
print(match)
match = re.search(pattern, 'ello 第一')
print(match)
程序运行结果:
匹配字符串边界
\b用于匹配字符串边界,分界符通常是空格,标点符号或者换行,以及要匹配的字符串本身的两端的两个位置即便没有任何符号但也是边界
import re
pattern = r'\bhe\b'
match = re.search(pattern, 'hello') # 无右边界,不匹配
print(match)
match = re.search(pattern, 'he llo') # 左边是字符串最左端,右边是空格,匹配成功
print(match)
match = re.search(pattern, ' hello ') # 左边是最左端,右边不是边界,不匹配
print(match)
match = re.search(pattern, 'he.llo') # 左边是最左端,右边是一个点符号,匹配成功
print(match)
程序运行结果:
__
4.使用finddall()进行匹配
findall()方法用于在整个字符串中搜索符合正则表达式的字符串,并以列表的方式返回。如如果匹配不成功则返回空列表。
re.finddall(pattern, string, [flags])
参数意义同上。
4.1位置匹配
import re
pattern = 'hello_\w+'
string = 'HELLO_world'
match = re.findall(pattern, string, re.I)
print(match)
string = 'abcHELLO_world'
match = re.findall(pattern, string)
print(match)
程序运行结果:
4.2贪婪匹配
python重复匹配时,正则总是尽可能多地匹配,默认是贪婪的。
- 常见的: .*
“.” 点星 是一种万能的匹配方式,点匹配除换行符以外的任意字符, 表示0次或任意次。
import re
pattern = 'https://.*/'
match = re.findall(pattern, 'https://www.hao123.com/')
print(match)
程序运行结果:
如果想单独获得点星部分的内容,则只需要给点星加个括号。使用(.*)的方式进行匹配。
import re
pattern = 'https://(.*)/'
match = re.findall(pattern, 'https://www.hao123.com/')
print(match)
爬虫中经常用到的例如,<div>.*<\div>
4.3非贪婪匹配
非贪婪匹配需要用到问号。
- .*?
需求:“匹配[‘123’]
import re
pattern = 'https://.*(\d+).com/' # 表达式,“.*”获取www.hao123.com
match = re.findall(pattern, 'https://www.hao123.com/')
print(match)
程序运行结果只匹配了一个[‘3’],没有满足需求。
因为点星会尽可能多的匹配,点星匹配了www.hao12,把3留给了(\d+)匹配。
想要得到[‘123’],需要把点星换成点星问(.*?)
import re
pattern = 'https://.*?(\d+).com/'
match = re.findall(pattern,'https://www.hao123.com/')
print(match) xc
程序运行结果:
点星问表示尽可能少的匹配,所以点星问匹配了www.hao,把123留给了(\d+)匹配。
需要注意的是,
如果需要匹配的结果在字符串尾部,非贪婪匹配可能匹配不到任何内容。示例:
import re
pattern = 'https://(.*?)'
match = re.findall(pattern, 'https://www.hao123.com/')
print(match)
pattern = 'https://(.*)'
match = re.findall(pattern, 'https://www.hao123.com/')
print(match)
程序运行结果:
(因为需要匹配的尽可能的少,所以匹配0个亦可满足。)
爬虫中经常用到的例如,<div>.*?<\div>
5.re模块其他常用方法
除了match(),search(),findall(),re模块还有如下常用方法:
5.1 compile()
compile(pattern[,flags])
根据正则表达式创建一个模板对象
import re
pat = re.compile(r'abc', re.I)
# res = pat.match('ABC123')
# print(res.group())
5.2split()
根据模板的匹配项来分割字符串
split(pattern, string[,maxsplit=0][,flags])
maxsplit为最大分割次数,分割二次则得到三个元素的列表。默认为0表示尽可能的多
s = '3+4-5*6/7'
print(re.split(r'[\+\-\*\/]', s, maxsplit=2))
5.3sub()
sub(pat, repl, string[,count=0, flags])
将字符串中所有的pat的匹配项用repl替换,返回完成替换后的新字符串。
s = 'i am zhangsan i study python'
r = re.sub(r'i', 'I', s)
print(r)