正则表达式

re模块

匹配

Python中提供了re模块,包含了所有正则表达式的功能

由于python字符串和正则表达式都使用\作为转义符,为了避免麻烦,我们推荐用r前缀来写python字符串就不用考虑转义问题


import re
result1=re.match(r'^\d{3}\-\d{3,8}$', '010-12345')
# 匹配成功返回 Match对象 否则返回None
print(result1) # <_sre.SRE_Match object; span=(0, 9), match='010-12345'>

result2=re.match(r'^\d{3}\-\d{3,8}$', '0qq10-12345')
print(result2) #None
if result2:
    print("匹配成功")
else: 
    print("匹配失败")

切分字符串

# 用任意多个空格切分字符串
re.split(r'\s+', 'a b   c') # ['a', 'b', 'c']

# 用空格或者空格加逗号分隔字符串
re.split(r'[\s\,]+', 'a,b, c  d') # ['a', 'b', 'c', 'd']

分组

正则表达式的分组功能,其表达式中的()就是要提取的分组

m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')

m.group(0) #'010-12345'
 m.group(1) # '010'
 m.group(2) # '12345'

group(0)永远是原始字符串

贪婪匹配

正则表达式默认是贪婪匹配,匹配尽可能多的字符创

re.match(r'^(\d+)(0*)$', '102300').groups()
# ('102300', '')
# 因为\d+ 贪婪匹配导致0*匹配到空字符串

re.match(r'^(\d+?)(0*)$', '102300').groups() # ('1023', '00')
# 添加了?让\d+处于非贪婪匹配