1. re模块中的一些方法
1.1 常用方法
- match和search是只返回第一个匹配的结果或者返回NONE
- findall返回所有匹配的结果
# !/usr/bin/python
# Filename: test.py
# Data : 2020/07/16
# Author : --king--
# ctrl+alt+L自动加空格格式化
import re
# 以下是re中match,search,findall的定义
# 1. match
# 从字符串开始部分进行匹配,如果匹配成功,返回一个匹配结果,如果没匹配到返回NONE
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).match(string)
# 2. search
# 对整个字符串进行匹配,如果匹配成功,返回一个匹配结果,如果没匹配到返回NONE
def search(pattern, string, flags=0):
"""Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).search(string)
# 3. findall
# 对整个字符串进行匹配,返回字符串中所有非重叠匹配的列表。
# 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
# 注意:findall没有group方法,返回值为列表
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
return _compile(pattern, flags).findall(string)
1.2 flag匹配模式
1.3 其他方法
- compile(pattern, flags=0)
这个⽅法是re模块的工厂法,⽤于将字符串形式的正则表达式编译为Pattern模式对象,可以实现更加效率的匹配。第二个参数flag是匹配模式 使用compile()完成一次转换后,再次使用该匹配模式的时候就不能进行转换了。经过compile()转换的正则表达式对象也能使用普通的re⽅法 - split(pattern, string, maxsplit=0, flags=0)
re模块的split()方法和字符串的split()方法很相似,都是利用特定的字符去分割字符串。但是re模块的split()可以使用正则表达式,因此更灵活,更强大
split有个参数maxsplit,用于指定分割的次数 - sub(pattern, repl, string, count=0, flags=0)
sub()方法类似字符串的replace()方法,用指定的内容替换匹配到的字符,可以指定替换次数
1.4 分组
- 分组功能
Python的re模块有一个分组功能。所谓的分组就是去已经匹配到的内容再筛选出需要的内容,相当于二次过滤。实现分组靠圆括号(),而获取分组的内容靠的是group()、groups()
# !/usr/bin/python
# Filename: test.py
# Data : 2020/07/16
# Author : --king--
# ctrl+alt+L自动加空格格式化
import re
text = 'apple price is $99,orange price is $88'
result = re.search('.+(\$\d+).+(\$\d+)',text)
# 匹配整个分组
print(result.group())
print(result.group(0))
# 匹配第一个分组
print(result.group(1))
# 匹配第二个分组
print(result.group(2))
# groups()返回所有分组
print(result.groups())
apple price is $99,orange price is $88
apple price is $99,orange price is $88
$99
$88
(’$99’, ‘$88’)
2. 匹配字符
2.1 元字符
- 元字符
- 一些无法书写或者具有特殊功能的字符,采用在前面加斜杠""进行转义的方法。
2.2 预定义字符集
- 正则表达式中的一些表示方法,可以同时匹配某个预定义字符集中的任意一个字符。比如,表达式\d可以匹配任意一个数字。虽然可以匹配其中任意字符,但是只能是一个,不是多个。
2.3 重复匹配
- 为了简化匹配规则的写法,引入了重复匹配的一些表达式