1.描述复杂规则的工具
search()方法用于在字符串中搜索正则表达式模式第一次出现的位置
>>> import re
>>> re.search(r'FishC','I love FishC.com!')
<_sre.SRE_Match object; span=(7, 12), match='FishC'>
>>> 'I love FishC.com!'.find('FishC')
7
>>> re.search(r'\d\d\d\.\d\d\d\.\d\d\d\.\d\d\d','192.168.111.101')
<_sre.SRE_Match object; span=(0, 15), match='192.168.111.101'>
>>> re.search(r'[aeiou]','I love 123 FishC.com!')
<_sre.SRE_Match object; span=(3, 4), match='o'>
>>> re.search(r'[2-9]','I love 123 FishC.com!')
<_sre.SRE_Match object; span=(8, 9), match='2'>
>>>
匹配0-255中的任意一个数:
>>> re.search(r'[01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5]','1')
<_sre.SRE_Match object; span=(0, 1), match='1'>
>>> re.search(r'[01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5]','17')
<_sre.SRE_Match object; span=(0, 2), match='17'>
>>> re.search(r'[01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5]','198')
<_sre.SRE_Match object; span=(0, 3), match='198'>
>>>
匹配IP地址:
>>> re.search(r'(([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])\.){3}([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])','198.167.1.102')
<_sre.SRE_Match object; span=(0, 13), match='198.167.1.102'>
>>> re.search(r'(([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])\.){3}([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])','198.168.101.1')
<_sre.SRE_Match object; span=(0, 13), match='198.168.101.1'>
>>>
{n}代表重复的n次,{n,m}代表可以重复n次或者m次
异常检测:
import urllib.request
import urllib.error
req = urllib.request.Request("http://www.bdu1.com/")
try:
urllib.request.urlopen(req)
#except urllib.error.URLError as e:
#except urllib.error.HTTPError as e:
print(e.reason)
# print(e.code)
# print(e.read())