python正则表达式

一、常用方法

findall:匹配所有符合规律的内容,返回包含结果的列表

search:匹配并提取第一个符合规律的内容,返回一个正则表达式对象(Object)

sub:替换符合规律的内容,返回替换后的值。

S:表示多行匹配

注意:findall与search的区别:

findall会遍历整个加载范围里的内容,并逐一返回匹配到的内容;

而search一旦匹配到指定内容就不再往下匹配,返回结果,搜索结束。

二、常用符号:

.号:匹配任意字符,换行符 除外

>>> import re
>>> a='xy123'
>>> b=re.findall('x.',a)
>>> print (b)
['xy']
>>> b=re.findall('x..',a)
>>> print (b)
['xy1']

*号:匹配前一个字符0次或无限次

>>> a='xyxy123'
>>> b=re.findall('x*',a)
>>> print (b)
['x', '', 'x', '', '', '', '', '']

?号:匹配前一个字符0次或1次

>>> a='xyxy123'
>>> b=re.findall('x.?',a)
>>> print b
['x', '', 'x', '', '', '', '', '']

注意:' '表示是匹配0次

+号:匹配前一个字符至少一次(一次或多次)

>>> a='xyxy123'
>>> b=re.findall('x+',a)
>>> print b
['x', 'x']

.*号:贪心算法

>>> import re
>>> secret_code='hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse'
>>> b=re.findall('xx.*xx',secret_code)
>>> print b
['xxIxxfasdjifja134xxlovexx23345sdfxxyouxx']

.*?号:非贪心算法

>>> import re
>>>secret_code='hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse'
>>> b=re.findall('xx.*?xx',secret_code)
>>> print b
['xxIxx', 'xxlovexx', 'xxyouxx']

():括号内的数据作为结果返回

>>> import re
>>>secret_code='hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse'
>>> b=re.findall('xx(.*?)xx',secret_code)
>>> print b
['I', 'love', 'you']

#匹配纯数据方法举例(d+)

>>> a='asdfefrg137143fdfhxs4321ddfdvsdf543dd'
>>> b=re.findall('(d+)',a)
>>> print b
['137143', '4321', '543']

 当匹配指定内容是,若遇到具有特殊意义的字符,如|、 、?等,需要用去掉特定含义。

s='>1ABA:A|PDBID|CHAIN|SEQUENCE'
re.findall('>(.*?)|',s)
['1ABA:A']

search()和group()配套使用

正则表达式中,group()用来提出分组截获的字符串,()用来分组

import re
a = "123abc456"
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0)   #123abc456,返回整体
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1)   #123
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2)   #abc
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3)   #456

分析:

1. 正则表达式中的三组括号把匹配结果分成三组

  •  group() 同group(0)就是匹配正则表达式整体结果
  •  group(1) 列出第一个括号匹配部分,group(2) 列出第二个括号匹配部分,group(3) 列出第三个括号匹配部分。

2. 没有匹配成功的,re.search()返回None

3. 当然郑则表达式中没有括号,group(1)肯定不对了。

实战--制作文本爬虫

目标网址:http://www.imtech.res.in/raghava/sarpred/data/Manesh-215/PSSM/

目标内容:提取指定的文件内容

实现原理:

1.保存网页源代码

2.python读取文件加载源代码

3.正则表达式提取

4.写#coding=utf-8


import urllib
import re

def getHtml(url):
    page=urllib.urlopen(url)
    html=page.read()
    return html
    
def getReq(html):
reg1
=r'href="(.*?.mtx)">' reg2=r'href="(.*?).mtx">' mtx=re.compile(reg1) title=re.compile(reg2) mtxlist=re.findall(mtx,html) titlelist=re.findall(title,html) fp=open('D://Manesh-215.txt','w') i=0 for requrl in mtxlist: strurl='http://www.imtech.res.in/raghava/sarpred/data/Manesh-215/PSSM/'+requrl mtxpage=urllib.urlopen(strurl) mtxhtml=mtxpage.readlines() st=">query | "+titlelist[i]+" | Length="+mtxhtml[0] fp.write(st) fp.write(mtxhtml[1]) i=i+1 fp.close()
原文地址:https://www.cnblogs.com/chaofn/p/4590522.html