Python爬虫之正則表達式

1.经常使用符号

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

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

     ?

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

     .*  :贪心算法。尽可能的匹配多的字符

    .*?  :非贪心算法

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

2.经常用法

      findall:匹配全部符合规律的内容。返回包括结果的列表

     Search:匹配并提取第一个符合规律的内容,返回一个正則表達式对象

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

3.使用演示样例

     3.1  . 的使用举例,匹配随意字符,换行符 除外

import re      #导入re库文件
a = 'xy123'
b = re.findall('x..',a)
print b
       打印的结果为:['xy1'] 。每一个 . 表示一个占位符

     3.2   * 的使用举例。匹配前一个字符0次或无限次

a = 'xyxy123'
b = re.findall('x*',a)
print b
      打印的结果为:['x', '', 'x', '', '', '', '', '']     

     3.3  ? 的使用举例,匹配前一个字符0次或1次

a = 'xy123'
b = re.findall('x?

',a) print b

     打印的结果为:['x', '', '', '', '', ''] 

     3.4  .* 的使用举例

secret_code = 'hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse'
b = re.findall('xx.*xx',secret_code)
print b
     打印的结果为:['xxIxxfasdjifja134xxlovexx23345sdfxxyouxx']

     3.5  .*?的使用举例

secret_code = 'hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse'
c = re.findall('xx.*?

xx',secret_code) print c

      打印的结果为:['xxIxx', 'xxlovexx', 'xxyouxx']

     3.6  ()的使用举例

secret_code = 'hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse'
d = re.findall('xx(.*?)xx',secret_code)
print d
      打印的结果为:['I', 'love', 'you']  。括号内的数据作为返回的结果

     3.7  re.S的使用举例

s = '''sdfxxhello
xxfsdfxxworldxxasdf'''
d = re.findall('xx(.*?)xx',s,re.S)  
print d
      打印的结果为:['hello ', 'world']  ,re.S的作用是使 . 在匹配时包含       

     3.8 findall的使用举例

s2 = 'asdfxxIxx123xxlovexxdfd'
f2 = re.findall('xx(.*?)xx123xx(.*?)xx',s2)
print f2[0][1]
      打印的结果为:love  
     这时f2为含有一个元组的列表,该元组包括两个元素,该元组中的两个元素为两个()匹配到的内容,假设s2包括多个'xx(.*?

)xx123xx(.*?

)xx'这种子串。则f2包括多个元组

     3.9 search的使用举例

s2 = 'asdfxxIxx123xxlovexxdfd'
f = re.search('xx(.*?)xx123xx(.*?

)xx',s2).group(2) print f

       打印的结果为:love
    .group(2) 表示返回第二个括号匹配到的内容,假设是 .group(1), 则打印的就是:I

     3.10 sub的使用举例

s = '123rrrrr123'
output = re.sub('123(.*?)123','123%d123'%789,s)
print output
       打印的结果为:123789123   
     当中的%d类似于C语言中的%d,假设 output=re.sub('123(.*?

)123','123789123',s),输出结果也为:123789123

     3.11 d 的使用举例。用于匹配数字

a = 'asdfasf1234567fasd555fas'
b = re.findall('(d+)',a)
print b
       打印的结果为:['1234567', '555']   , d+  能够匹配数字字符串


原文地址:https://www.cnblogs.com/cynchanpin/p/7094041.html