python 正则表达式 之re.findall

时间:2023-01-09 22:33:51

python 正则表达式 re findall 方法能够以列表的形式返回能匹配的子串。

re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。先看个简单的代码:

import re
 
p = re.compile(r'\d+')
print p.findall('one1two2three3four4')
 
### output ###
# ['1', '2', '3', '4']

稍微复杂点比如:
info = '<a href="http://www.baidu.com">baidu</a>' 我们的需求是通过正则表达式提取网址和锚文本,那可以用到
findall()

import re
relink =  '<a href="(.*)">(.*)</a>'
info =  '<a href="http://www.baidu.com">baidu</a>'
cinfo = re.findall(relink,info)
print cinfo

输出的结果:[('http://www.baidu.com', 'baidu')] 返回的是一个列表,列表里面是匹配的结果形成的元组形式


例子function:

def get_yizhe_info(url):  # url weiyigecanshu
#url='http://book.douban.com/subject/6082808/?from=tag_all' # For Test
req = urllib2.Request(url, headers=hds2[np.random.randint(0,len(hds2))])
html = urllib2.urlopen(req).read()
html = html.replace('\n', '')
#print html
try:
reg_temp='<span class="pl"> 译者</span>: *?(.*?)<br/>'
temp=re.findall(reg_temp,html)
print temp
if temp:
reg_author = '<a class="" href=".*?">(.*?)</a>'
name = re.findall(reg_author, temp[0])
print name
str=''
for na in name:
str=na+'/'+str
str = str.replace(str,str[:-1])
except:
str = '暂无'
return str