平时遇到的一些小问题

2018.09.25

关于re.match()和re.search()的一些使用说明,主要要注意的是match的话是必须一开始就要从头匹配上,而search的话可以只要中间有一段匹配上就行了

注意一下

print(re.match('super','superstition').span())

print(re.match('super','insuperable'))

print(re.search('super','superstition').span())

print(re.search'super','insuperable').span()

 span决定是不是在起始位置匹配,加上就是从头开始

re.match(pattern, string, flags=0)

flag中
  1. re.I 忽略大小写
  2. re.L 表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境
  3. re.M 多行模式
  4. re.S 即为 . 并且包括换行符在内的任意字符(. 不包括换行符)
  5. re.U 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库
  6. re.X 为了增加可读性,忽略空格和 # 后面的注释

group()用来提取分组截获的字符串

小技巧

import re
s = '1102231990xxxxxxxx'
res = re.search('(?P<province>\d{3})(?P<city>\d{3})(?P<born_year>\d{3})',s)
print(res.groupdict())


{'province': '110', 'city': '223', 'born_year': '199'}
直接将匹配结果直接转为字典模式,方便使用。


这篇文章对于正则描写的十分详细,请随意查阅
http://www.runoob.com/python/python-reg-expressions.html

猜你喜欢

转载自www.cnblogs.com/xingnie/p/9703547.html