首页 > 编程语言 > 详细

python正则表达式

时间:2015-06-20 15:37:01      阅读:369      评论:0      收藏:0      [点我收藏+]

一、常用方法

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

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

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

S:表示多行匹配

注意:findall与search的区别:

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

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

二、常用符号:

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

>>> 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]

 

实战--制作文本爬虫

目标网址: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
=rhref="(.*?\.mtx)"> reg2=rhref="(.*?)\.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()

 

python正则表达式

原文:http://www.cnblogs.com/chaofn/p/4590522.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!