我正在使用聊天機器人。我希望它發佈匹配的數據從一個API時,只要鏈接到圖像板上的畫廊發佈。圖庫鏈路看起來像這樣快速提取URL列表並檢查有效性的方法
https://example.com/a/1234/a6fb1049/
其中1234是一個正數(ID)和a6fb1049是固定長度10(令牌)的十六進制字符串。 現在我只能夠處理以圖庫鏈接開始的消息。
if message_object.content.startswith("https://example.com/a/"):
我正在尋找一個快速的方式來處理消息字符串,因爲每次發送消息,這將被調用。
if message_object.content.startswith("https://example.org/a/"):
temp = message_object.content.split("/")
# Check if link is actually a valid link
if temp[2] == "example.org" and temp[3] == "a" and 0 < int(temp[4]) and len(temp[5]) == 10:
gallery_id = temp[4]
gallery_token = temp[5]
response = requests.post(url, payload, json_request_headers)
我想過使用urllib.parse.urlparse和posixpath.split分割字符串,並檢查不同的子串,但我覺得這是低效的。
因爲我對Regex不太好,這就是我想出來的。
searchObj = re.search(r'https://example.org/a/(.*)/(.*)/', message)
如果只有一個匹配的模式,它是正確的,但它是正確的,但只要有兩個鏈接,這已經失敗。
我寧願讓匹配列表中的鏈接的所有消息,然後迭代列表並檢查頁面的標題,如果鏈接有效。然後創建一個API請求來檢索數據。
匹配Stackoverflow上的URL的正則表達式不顯示如何匹配這些特定的情況,所以我很抱歉,如果這是一個新問題。
「我寧願讓所有匹配列表中的鏈接的消息,然後遍歷列表」 - 聽起來像你需要['re.findall'](https://docs.python.org/2/library/ re.html#re.findall) – asongtoruin