一、基础知识
IP地址
二、 常用函数
前提:正则表达式库 re (python专用库)
1、search查找从字符串中查找匹配对象
ls = re.search(r'[1-9]\d{5}','BIT 100081')
if ls:
print(ls.group(0))
print(ls)
结果
100081
<re.Match object; span=(4, 10), match='100081'>
2、match从字符串的起始开始比较,如果前几个字符不同,该字符串后面不再比较
re.match(r'[1-9]\d{5}','BIT 100081')
结果: (无)
re.match(r'[1-9]\d{5}','100081asdsa')
结果:
<re.Match object; span=(0, 6), match='100081'>
3、split()从string里剔除匹配到的字符(返回列表类型)
ls = re.split(r'[1-9]\d{5}','BIR100081 rpt8797226355')
print(ls)
结果:
['BIR', ' rpt', '6355']
4、finditer用循环迭代的方式返回结果
for i in re.finditer(r'[1-9]\d{5}','Btt100081 1545456'):
if i:
print(i.group(0))
结果:
100081
154545
5、sub将string中匹配(pattern)到的字符串替换成reple
re.sub(r'[1-9]\d{5}',':abc','BIR100081 rpt8797226355')
结果:
'BIR:abc rpt:abc6355'
6、预编译compile()
pat = re.compile(r'[1-9]\d{5}')
r = pat.search("aasf5456534")
print(r.group(0))
结果:
545653
7、特殊用法:Match对象
>>> ls = re.search(r'[1-9]\d{5}','BIT 100081 and5646878')
>>> ls.string
'BIT 100081 and5646878'
>>> ls.re
re.compile('[1-9]\\d{5}')
>>> ls.pos
0
>>> ls.endpos
21
>>> ls.group(0)
'100081'
>>> ls.span()
(4, 10)
>>> ls.end()
10
>>> ls.start()
4
(1)贪婪匹配与最小匹配
一般函数都采取贪婪匹配(返回最长的字符串)
>>> match = re.search(r'py.*N',"pyANBNCNDN")
>>> match.group(0)
'pyANBNCNDN'
>>> match = re.search(r'py.*?N',"pyANBNCNDN")
>>> match.group(0)
'pyAN'
三、常见实例
1、例如获取"view_price":"20"中的20这一数字
plist = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
2、获取含有英文字符数字以及特殊符号的字符
https://www.zhipin.com/job_detail/ef2ed6109002302603Z93d6-F1A~.html?ka=search_list_1
正则表达式为 .+job_detail/[\w-~]*\.html
https://www.zhipin.com/job_detail/54.html
正则表达式为 .+job_detail[/d].+\.html
3、获取含有英文字符数字
https://www.jianshu.com/p/c7642b6eb990
正则表达式 .*/p/[0-9a-z]{12}
[0-9a-z]{12}表示数字字符串重复12位数
注 .
1、*与.+的区别,在于.*匹配可有可无,但.+后面必须有字符
2、在做匹配的时候,字符串中间尽量使用非贪婪匹配,也就是用.*?叫来代替 .*
,以免出现
匹配结果缺失的情况。