1. 程式人生 > >爬蟲第一課:正則表示式符號與方法

爬蟲第一課:正則表示式符號與方法

第一課:正則表示式符號與方法

1.

. :匹配任意字元,換行符除外:

>>> import re

>>> a='xy123'

>>> b=re.findall('x',a)

>>> b

['x']

>>> b=re.findall('x...',a)
>>> b

['xy12']


所以,"."是一個佔位符


2.

* :匹配前一個字元0次或者無限次:

>>> import re
>>> a='xy123'
>>> b=re.findall('x*',a)
>>> b

['x', '', '', '', '', '']


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



3.

? : 匹配前一個字元0次或者1次:

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


4.

.* :貪心演算法:

>>> a
'fffxxIxxhyhxxlovexxhhhxxyouxxghh'
>>> b=re.findall('xx.*xx',a)
>>> b

['xxIxxhyhxxlovexxhhhxxyouxx']


5.

.*? :非貪心演算法:

>>> a
'fffxxIxxhyhxxlovexxhhhxxyouxxghh'
>>> b=re.findall('xx.*?xx',a)
>>> b
['xxIxx', 'xxlovexx', 'xxyouxx']



6.

() :匹配目標:

>>> a
'fffxxIxxhyhxxlovexxhhhxxyouxxghh'
>>> b=re.findall('xx(.*?)xx',a)
>>> b
['I', 'love', 'you']

提取出來了目標:I LOVE YOU 


再來看一個例子:

import re
s='ffsdxxhello\nxxfgfgxxworldxxhffh'

d=re.findall('xx(.*?)xx',s)

結果:>>> d

['fgfg']

注意,這裡換行了,而只尋找到了第二行。(我們的目標是找到hello world)

那麼怎麼避免這種情況呢?

答案:用.S

import re
s='ffsdxxhello\nxxfgfgxxworldxxhffh'

d=re.findall('xx(.*?)xx',s,re.S)

結果:>>> d

['hello\n', 'world']


接下來對比findall 與search 的區別:

>>> s2='asssxxIxx123xxlovexxdh'
>>> f=re.search('xx(.*?)xx123xx(.*?)xx',s2).group(2)
>>> f
'love'
>>> f=re.search('xx(.*?)xx123xx(.*?)xx',s2).group(1)
>>> f
'I'
>>> f=re.search('xx(.*?)xx123xx(.*?)xx',s2).group(0)
>>> f
'xxIxx123xxlovexx'
>>> f=re.search('xx(.*?)xx123xx(.*?)xx',s2).group(3)
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    f=re.search('xx(.*?)xx123xx(.*?)xx',s2).group(3)

IndexError: no such group


>>> f=re.findall('xx(.*?)xxgdgxx(.*?)xx',s2)

>>> f
[('I', 'love')]



接下來講解sub的使用:


sub的功能就是替換

>>> s='123hfhdfhdxhdhd123'

>>> output=re.sub('123(.*?)123','123789123',s)
>>> output
'123789123'
>>> output=re.sub('123(.*?)123','123%d123'%789,s)
>>> output

'123789123'

最好不要使用compile

匹配純數字的特殊方法:

\d+



>> a='dsgdgd1112255555555555hdhdgdgd'
>>> c=re.findall('(\d+)',a)

>>> c

['1112255555555555']


>>> b='dghgd11111111ysdysdys2222223ddh'

>>> dc=re.findall('(\d+)',b)
>>> dc
['11111111', '2222223']