python正则表达式(三)

时间:2023-03-08 17:35:34

表示边界

python正则表达式(三)

示例1:$

需求:匹配163.com的邮箱地址

#coding=utf-8

import re

# 正确的地址
ret = re.match("[\w]{4,20}@163\.com", "xiaoWang@163.com")
ret.group() # 不正确的地址
ret = re.match("[\w]{4,20}@163\.com", "xiaoWang@163.comheihei")
ret.group() # 通过$来确定末尾
ret = re.match("[\w]{4,20}@163\.com$", "xiaoWang@163.comheihei")
ret.group()

python正则表达式(三)

示例2: \b

>>> re.match(r".*\bver\b", "ho ver abc").group()
'ho ver' >>> re.match(r".*\bver\b", "ho verabc").group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group' >>> re.match(r".*\bver\b", "hover abc").group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

示例3:\B

>>> re.match(r".*\Bver\B", "hoverabc").group()
'hover' >>> re.match(r".*\Bver\B", "ho verabc").group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group' >>> re.match(r".*\Bver\B", "hover abc").group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group' >>> re.match(r".*\Bver\B", "ho ver abc").group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

匹配分组

python正则表达式(三)

示例1:|

需求:匹配出0-100之间的数字

#coding=utf-8

import re

ret = re.match("[1-9]?\d","")
ret.group() ret = re.match("[1-9]?\d","")
ret.group() # 不正确的情况
ret = re.match("[1-9]?\d","")
ret.group() # 修正之后的
ret = re.match("[1-9]?\d$","")
ret.group() # 添加|
ret = re.match("[1-9]?\d$|100","")
ret.group() ret = re.match("[1-9]?\d$|100","")
ret.group() ret = re.match("[1-9]?\d$|100","")
ret.group() ret = re.match("[1-9]?\d$|100","")
ret.group()

python正则表达式(三)

示例2:( )

需求:匹配出163、126、qq邮箱之间的数字

#coding=utf-8

import re

ret = re.match("\w{4,20}@163\.com", "test@163.com")
ret.group() ret = re.match("\w{4,20}@(163|126|qq)\.com", "test@126.com")
ret.group() ret = re.match("\w{4,20}@(163|126|qq)\.com", "test@qq.com")
ret.group() ret = re.match("\w{4,20}@(163|126|qq)\.com", "test@gmail.com")
ret.group()

python正则表达式(三)