1. 程式人生 > 實用技巧 >python re.match()用法相關 正則表示式

python re.match()用法相關 正則表示式

學習python爬蟲時遇到了一個問題,書上有示例如下:

import re

line='Cats are smarter than dogs'
matchObj=re.match(r'(.*)are(.*?).*',line)

if matchObj:
    print('matchObj.group():',matchObj.group())
    print('matchObj.group(1):', matchObj.group(1))
    print('matchObj.group(2):', matchObj.group(2))
else:
    print('No match!\n
')

書上的期望輸出是:

matchObj.group(): Cats are smarter than dogs
matchObj.group(1): Cats 
matchObj.group(2):smarter

但是我在電腦上跑了一遍得到的輸出卻是:

matchObj.group(): Cats are smarter than dogs
matchObj.group(1): Cats 
matchObj.group(2):

於是開始想辦法徹底搞清楚這個差別的原因所在。

首先要讀懂這幾行程式碼,而這一行程式碼的關鍵在於這一句:

matchObj=re.match(r'(.*)are(.*?).*
',line)

匹配的正則表示式是

(.*)are(.*?).*
前面的r表示的是匹配的字元不進行轉義,而要匹配的字串是line,也就是
Cats are smarter than dogs
後面使用group(num),個人理解是,按照正則表示式中的括號數可以捕獲得到對應數量的捕獲組,而呼叫group(num)就可以得到對應捕獲組的內容,
其中group(0)表示的是匹配的整個表示式的字串,在本例中就是‘Cats are smarter than dogs’。
參照網上可以搜到的符號的作用:
.匹配除換行符以外的任意字元
*重複之前的字元零次或更多次
?重複之前的字元零次或一次
那麼第一個括號的內容,應當就是匹配要匹配的字串中are之前的所有字元(除換行符),
而第二個括號的內容應當是匹配are之後的內容,但具體想指代什麼卻顯得有些不明確。
不明確的點就在於*和?這兩個符號的連用,根據優先順序這兩個符號是同一優先順序的,那麼應當按照順序生效,那麼如此翻譯的話,這一語句匹配的就是長度為0到無限大的任意字串,為了探清此時
程式判斷的具體內容,我們給匹配字串末尾的.*也加上括號以提取其內容,而後在輸出部分加上對應語句:
import re

line='Cats are smarter than dogs'
matchObj=re.match(r'(.*)are(.*?)(.*)',line)

if matchObj:
    print("matchObj.group():",matchObj.group())
    print("matchObj.group(1):", matchObj.group(1))
    print("matchObj.group(2):", matchObj.group(2))
    print("matchObj.group(3):", matchObj.group(3))
else:
    print('No match!\n')

得到的結果是:

matchObj.group(): Cats are smarter than dogs
matchObj.group(1): Cats 
matchObj.group(2): 
matchObj.group(3):  smarter than dogs

可見第二個括號裡的內容被預設為空了,然後刪去那個?,可以看到結果變成:

matchObj.group(): Cats are smarter than dogs
matchObj.group(1): Cats 
matchObj.group(2):  smarter than dogs
matchObj.group(3): 

那麼這是否就意味著?的預設值很可能是0次,那?這個符號到底有什麼用呢

今天歇了,明天再研究