2015-10-13 36 views
0
import re 

a = "AB01" 
m = re.compile(r"([A-Z]{2})(\s?_?\s?)([0-9]{2})") # note raw string 
g = m.match(a) 
if g: 
    g = m.match(a).group(1) + "-" + m.search(a).group(3) 
    print m.match(a).group() 
    print m.match(a).group(0) 
    print (m.match(a).group(0) == m.match(a).group()) 
    print g 

在上面的代碼,是基團m.match(a).group()的整個匹配,是相同m.match(a).group(0)?如果是這樣,哪個是首選用途?正則表達式匹配組(0)和組()相同嗎?

+0

要麼提出您的問題或不要,請停止對衝的第一句話。 – jonrsharpe

回答

1

the documentation

沒有參數,組1默認爲零(整場比賽是 返回)。

所以,是的; .group()給出與.group(0)相同的結果。


請注意,您正在測試編譯正則表達式的真實性,而不是它是否匹配,這似乎很奇怪。也許你的意思是:

a = "AB01" 
m = re.compile(r"([A-Z]{2})(\s?_?\s?)([0-9]{2})") # note raw string 
g = m.match(a) 
if g: 
    ... 

甚至只是:

... 
g = re.match(r"([A-Z]{2})(\s?_?\s?)([0-9]{2})", a) 
if g: 
    ... 

因爲有很少的好處在這種情況下進行編譯。

+0

哎呦錯過了那一個。我的代碼已更新 –

+0

@MrMysteryGuest請注意,這可以讓您將重複的「m.match(a)」 – jonrsharpe