Python笔记6(正则表达式、JSON、枚举)

  • 基础

正则表达式查询

 \d   匹配一个数字
 \w   匹配一个字母
 .    匹配任意字符
 *    匹配任意个字符(包括0个)
 +    匹配至少一个字符
 ?    匹配0个或1个字符
 {n}  匹配n个字符
 {n,m}匹配n-m个字符
 \s   匹配一个空格,也包括tab等空白符
 []  表示范围,比如[0-9a-zA-Z\_]
 A|B 匹配A或B
 ^   表示行的开头,^\d表示必须以数字开头
 $   表示行的结束,\d$表示必须以数字结束
 [^] 表示非范围
 (){n}   表示括号中组出现的次数

  • re模块
  1. Python字符串也使用\转义,建议使用r前缀的原生字符串
    2.使用
import re

# 返回Match对象或者None
match = re.match(r'^\d{3}\-\d{3,8}$', '010-123456')
if match:
    print('ok')
else:
    print('fail')
  1. 切分字符串:re.split
# 返回list
match2 = re.split(r'\s+', 'a b       c')
print(match2)

match3 = re.split(r'[\s,\,,\;]+', 'a,b, ;c    d  e')
print(match3)
  1. 分组:()表示要提取分组
group(0)为原始字符串

# 返回Match对象或者None
match4 = re.match(r'^(\d{3})\-(\d{3,8})$', '010-123456')
print(match4) # 
print(match4.group(0)) # 010-123456
print(match4.group(1)) # 010
print(match4.group(2)) # 123456
  1. 贪婪匹配、非贪婪匹配
正则默认为贪婪匹配,非贪婪匹配需要加?

# 贪婪匹配
match5 = re.match(r'^(\d+)(0*)$', '1023000')
print(match5.groups()) # ('1023000', '')

# ?非贪婪匹配
match6 = re.match(r'^(\d+?)(0*)$', '1023000')
print(match6.groups()) # ('1023', '000')
  1. 编译
如果一个正则表达式要重复使用几千次,出于效率的考虑,
我们可以预编译该正则表达式,接下来重复使用时就不需要编译这个步骤了,直接匹配。
# 编译
re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
# 使用
list1 = re_telephone.match('010-12345').groups()
# ('010', '12345')
list2 = re_telephone.match('010-22323424').groups()
# ('010', '22323424')
  1. 查找 findall()
# 找出3位连续数字
list3 = re.findall('\d{3}', r'DIF23HI3309U22B3232923N3N3323L3')
print(list3) # ['330', '323', '292', '332']
  1. findall()中flag参数使用
设置大小写参数等
  1. 查找之后替换字符串:sub(),还可以接受一个函数,来处理每次匹配到的结果,然后返回
s1 = 'A823YCHU302382322J3'


def convert(value):
    matched = value.group()
    if int(matched) >= 6:
        return '9'
    else:
        return '6'


r1 = re.sub(r'\d', convert, s1)
print(r1)  # A966YCHU666696666J6

findall、match、search区别:

  1. match:从首字母开始匹配,只匹配一次,返回一次的匹配结果
  2. search:搜索整个字符串
  3. findall:查找整个字符串,返回所有匹配结果

Json

  • 轻量级的数据交换格式

枚举

  • 枚举也是一个类
  • 特点:
1. 值不可变
2. 可以确定唯一的标签
  • 枚举的值相同的话,另外一个是上一个的枚举的别名
  • 枚举使用建议:
@unique
class VIP(Enum):
    YELLOW = 1
    GREEN = 2
    RED = 3

1. 需要将枚举存入数据库等,建议存入枚举对应的值
2. 从数据库中取出枚举的值,使用 类名(值) 比如:VIP(1) 即可得到对应的枚举标签
  • 枚举不能实例化,实现的是一种单例模式

你可能感兴趣的:(Python笔记6(正则表达式、JSON、枚举))