python 匹配url中是否存在IP地址的方法

來源:互聯網
上載者:User
這篇文章主要介紹了關於python 匹配url中是否存在IP地址的方法,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

因為需要檢測一個一個連結中是否包含了IP地址,在這裡需要使用到Regex ,python完美的支援了Regex,在這裡使用re模組來完成,對Regex並不是很熟練,每次都是需要用的時候現查一下然後寫一下,這裡給出來自己的代碼以及借鑒別人的匹配模式

#!/usr/bin/env python# -*- coding: utf-8 -*-'''功能:對於給定的URL,檢測其中是否包含IP'''import redef ip_exist_two(one_url):compile_rule = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])')match_list = re.findall(compile_rule, one_url)if match_list:print match_listelse:print 'missing................'def ip_exist_one(one_url):compile_rule = re.compile(r'\d+[\.]\d+[\.]\d+[\.]\d+') match_list = re.findall(compile_rule, one_url)if match_list:print match_listelse:print 'missing................'if __name__ == '__main__':ip_list = ['http://101.23.45.67/sd/sd.html','http://www.baidu.com','http://34.54.65.3/dsdfjkk.htm','http://dhj.fdjjd.com/78078979/dsdfjkk.htm']for one_url in ip_list:ip_exist_one(one_url)print '****************************************************'for one_url in ip_list:ip_exist_two(one_url)

ip_exist_one(one_url)裡面是自己的匹配模式,個人感覺更賤練一下,ip_exist_two(one_url)裡面是網上提供的匹配IP的Regex,感覺比較繁雜一下,不過實驗了一下都是可以正確匹配出來結果的。

下面是列印出來的結果

['101.23.45.67']missing................['34.54.65.3']missing................****************************************************['101.23.45.67']missing................['34.54.65.3']missing................

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.