python 正则表达式 之re.findall

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 = 'baidu' 我们的需求是通过正则表达式提取网址和锚文本,那可以用到
findall()

import re
relink =  '(.*)'
info =  'baidu'
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=' 译者: *?(.*?)
' temp=re.findall(reg_temp,html) print temp if temp: reg_author = '(.*?)' 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


你可能感兴趣的:(python)