国庆7天,没有追逐诗和远方, 在公司把python的前置知识理了一下。其中,正则 匹配这块忘记的差不多了,就重新学习了一下。
1. 正则表达式
正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些字符、以及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串用来表达对字符串的一种过滤逻辑”,简单来说,就是提取字符串中的特定的内容。
常见的正则语法:
语法 | 说明 | 表达式实例 |
一般字符 | 匹配自身 | abc |
. | 匹配换行符以外的字符 | a.c |
[..] | 匹配中括号中的字符 | a[ bdc]e |
\ | 转义字符 | |
\d | 匹配数字 | a\dc |
\w | 字母数字下划线 | |
* | 匹配0次或者无限次 | abc* |
+ | 匹配1次或者无限多次 | abc+ |
? | 匹配0次或者1次 | abc? |
{m} | 匹配前一个字符m次 | ab{2}c |
{m,n} | 匹配m次到n次 | ab{2,4}c |
^ | 匹配开头 | ^abc |
| | | | 或的意思 |
2. 正则模块的使用
2.1 正则模块
import re
# compile 创建模式
pattern = re.compile('\w?') # 匹配一个数字0次或者1次
# match 方法 从头开始匹配,匹配成功就返回一个对象,返回失败就返回None, 只返回一个对象
re.match('[abc]\d', 'a1fdsadf3').group()
# search匹配一次
re.search('[abc]{1}', '123a1b2c3').group()
# findall 遍历匹配
pa = re.compile('[a-zA-Z]{1}')
strs = '123abc456'
print(re.findall(pa, strs))
print(pa.findall(strs))
2.2 常见的正则函数
函数 | 说明 |
match | zip匹配一次,且从头开始匹配 |
search | 从任何地方开始匹配,职匹配一次 |
findall | 迭代匹配字符串,返回一个列表(缺点:只返回了分组的结果) |
finditer | 可以遍历出所有的对象 |
split | 按照给定格式进行分割 |
sub/subn | 按照给定的格式进行替换 |
pattern = re.compile('(\d+) [a-z]+')
strs = '123 abc,456 efg'
print(pattern.findall(strs)) # 只返回了分组的结果
pattern1 = re.compile('\d+ [a-z]+')
pattern1.findall(strs)
# 输出
['123', '456']
['123 abc', '456 efg']
# -------------------------------------------
for i in pattern.finditer(strs):
print(i.group(0)) # 0返回所有的对象
print('----')
print(i.group(1)) # 只返回分组的结果
# 输出
123 abc
----
123
456 efg
----
456
# --------------------------------------------
# split 分割字符串
re.split('\d', 'a1b2c3')
# 输出
['a', 'b', 'c', '']
# --------------------------------------------
# 替换
re.sub('\d+', '***', 'a1b2c3')
#输出
'a***b***c***'
2.2.1 引用分组
# 引用分组
pattern = re.compile('(\d+) ([a-z]+)')
strs = '123 abc,456 efg'
for item in pattern.finditer(strs):
print('all-group', item.group())
print('1th-group', item.group(1))
print('2nd-group', item.group(2))
print('---')
pattern.sub(r'\2 \1', strs) # r为转义字符
# 输出
all-group 123 abc
1th-group 123
2nd-group abc
---
all-group 456 efg
1th-group 456
2nd-group efg
---
'abc 123,efg 456'
3. 贪婪模式与非贪婪模式
- 贪婪模式: 在整个表达式匹配成功的前提下,尽可能多的匹配
- 非贪婪模式: 在整个表达式匹配成功的前提下,尽可能少的匹配
# 贪婪模式,尽可能多的匹配
strs = 'aaa<p>hello</p>bbb<p>world</p>ccc'
pattern = re.compile('<p>.*</p>')
print(pattern.findall(strs))
# 非贪婪模式,尽可能少的匹配
pattern2 = re.compile('<p>.*?</p>')
print(pattern2.findall(strs))
# 输出
['<p>hello</p>bbb<p>world</p>']
['<p>hello</p>', '<p>world</p>']
4. 匹配中文
# 匹配中文字符
pattern = re.compile('[\u4e00-\u9fa5]+')
strs = '你好,hello, 帅哥'
print(pattern.findall(strs))
# 输出
['你好', '帅哥']
# -----------------------------------------------
strs = '你好hello, 帅哥'
pattern3 = re.compile('\w+')
pattern3.findall(strs)
# 输出
['你好hello', '帅哥']