我有一個字符串,我想在一開始和結尾匹配一個搜索模式。如何才能做到這一點?如何在Python的正則表達式中匹配開始和結束?
比方說,我們有一個字符串,如:
string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
我想要做這樣的事情:
re.search("^ftp:// & .jpg$" ,string)
顯然,這是不正確的,但我希望它橫跨得到我的觀點。這可能嗎?
我有一個字符串,我想在一開始和結尾匹配一個搜索模式。如何才能做到這一點?如何在Python的正則表達式中匹配開始和結束?
比方說,我們有一個字符串,如:
string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
我想要做這樣的事情:
re.search("^ftp:// & .jpg$" ,string)
顯然,這是不正確的,但我希望它橫跨得到我的觀點。這可能嗎?
re.match
將match the string at the beginning,而相比之下,re.search
:
re.match(r'(ftp|http)://.*\.(jpg|png)$', s)
有兩點需要注意這裏:
r''
用於字符串字面意思是在正則表達式中加入反斜槓string
是一個標準的模塊,所以我選擇了s
作爲變量r = re.compile(...)
內置狀態機一次,然後用r.match(s)
事後匹配字符串如果你願意,你也可以使用urlparse
模塊解析URL爲你(雖然你仍然需要提取擴展名):
>>> allowed_schemes = ('http', 'ftp')
>>> allowed_exts = ('png', 'jpg')
>>> from urlparse import urlparse
>>> url = urlparse("ftp://www.somewhere.com/over/the/rainbow/image.jpg")
>>> url.scheme in allowed_schemes
True
>>> url.path.rsplit('.', 1)[1] in allowed_exts
True
如何根本不使用正則表達式?
if string.startswith("ftp://") and string.endswith(".jpg"):
你不覺得這個更好嗎?
還可以支持開始和結束多種選擇:
if (string.startswith(("ftp://", "http://")) and
string.endswith((".jpg", ".png"))):
我會,但它更復雜,因爲有一些有效的開始和結束序列。如果我知道如何做這個簡單的例子,我可以使它適應更復雜的現實。 :) – 2012-03-30 16:40:44
@Google:你也可以查詢多個字符串,看看我的更新。 – 2012-03-30 16:42:54
嘗試
re.search(r'^ftp://.*\.jpg$' ,string)
如果你想有一個正則表達式搜索。請注意,您必須跳過這段時間,因爲它在正則表達式中有特殊含義。
不要貪心,使用^ftp://(.*?)\.jpg$
import re
s = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
print(re.search("^ftp://.*\.jpg$", s).group(0))
你認爲要檢查文檔嗎? – Marcin 2012-03-30 16:42:02