表示邊界 示例1:$ 需求:匹配163.com的郵箱地址 示例2: \b 示例3:\B 匹配分組 示例1:| 需求:匹配出0-100之間的數字 示例2:( ) 需求:匹配出163、126、qq郵箱之間的數字 ...
表示邊界
示例1:$
需求:匹配163.com的郵箱地址
#coding=utf-8 import re # 正確的地址 ret = re.match("[\w]{4,20}@163\.com", "[email protected]") ret.group() # 不正確的地址 ret = re.match("[\w]{4,20}@163\.com", "[email protected]") ret.group() # 通過$來確定末尾 ret = re.match("[\w]{4,20}@163\.com$", "[email protected]") ret.group()
示例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'
匹配分組
示例1:|
需求:匹配出0-100之間的數字
#coding=utf-8 import re ret = re.match("[1-9]?\d","8") ret.group() ret = re.match("[1-9]?\d","78") ret.group() # 不正確的情況 ret = re.match("[1-9]?\d","08") ret.group() # 修正之後的 ret = re.match("[1-9]?\d$","08") ret.group() # 添加| ret = re.match("[1-9]?\d$|100","8") ret.group() ret = re.match("[1-9]?\d$|100","78") ret.group() ret = re.match("[1-9]?\d$|100","08") ret.group() ret = re.match("[1-9]?\d$|100","100") ret.group()
示例2:( )
需求:匹配出163、126、qq郵箱之間的數字
#coding=utf-8 import re ret = re.match("\w{4,20}@163\.com", "[email protected]") ret.group() ret = re.match("\w{4,20}@(163|126|qq)\.com", "[email protected]") ret.group() ret = re.match("\w{4,20}@(163|126|qq)\.com", "[email protected]") ret.group() ret = re.match("\w{4,20}@(163|126|qq)\.com", "[email protected]") ret.group()