2013-01-02 26 views
2

我不太瞭解正則表達式,我正在努力學習它們。我正在使用Python,並且需要使用re.compile來創建一個匹配任何以變量字符串開頭的字符串的正則表達式。該字符串是變量url。目前我有re.compile('%s*'%url),但它似乎不工作。我究竟做錯了什麼?Python的正則表達式去匹配以字符串開頭的任何字符串

+0

能否請您發表您的當前代碼,看看是否可以找到這個錯誤? – Hairr

回答

4

使用re.escape(url)

In [15]: import re 

In [16]: url = 'http://stackoverflow.com' 

In [17]: pat = re.compile(re.escape(url)) 

In [18]: pat.match('http://stackoverflow.com') 
Out[18]: <_sre.SRE_Match object at 0x8fd4c28> 

In [19]: pat.match('http://foo.com') is None 
Out [19]: True 
0

雖然正則表達式將針對這種情況工作,爲什麼不使用str.startswith()?使事情變得更簡單,並且已經使用python構建了這種情況。它也凝結的是必須與你的代碼,如編譯,匹配等所做的一切,所以,代替正則表達式的,這是你的代碼可以是什麼樣子:

url = "http://example.com/" 
string = "http://example.com is a great site! Everyone check it out!" 
if string.startswith(url): 
    print 'The string starts with url!' 
else: 
    print "The string doesn't start with url. Very unfortunate." 
+0

這將是太棒了,但我實際上使用它來從數據庫中獲得匹配該正則表達式的字段 – chromedude

+0

如果它是正則表達式或內置類型,它會產生什麼區別? – Hairr

+0

我同意,如果你只是試圖匹配一個字符串的URL開始,正則表達式是矯枉過正。 – goji

相關問題