本文介绍了Python识别字符串中的IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这段代码上遇到了很多麻烦:
I'm having a lot of trouble with this segment of code:
command = "!ip"
string = "!ip 127.0.0.1"
if command in string:
那就是我被困住的地方.在第一个if语句之后,我需要另一个来识别任何IP地址,而不是127.0.0.1.最简单的方法是什么?
That's where I get stuck. After the first if statement I need another one to recognize any IP address just not 127.0.0.1. What's the easiest way of doing this?
推荐答案
我会使用正则表达式来尝试一下,其中正则表达式(?:[0-9]{1,3}\.){3}[0-9]{1,3}
是IP地址的简单匹配.
I would give it a shot using regular expressions, where the regular expression (?:[0-9]{1,3}\.){3}[0-9]{1,3}
is a simple match for an IP address.
ip = '127.0.0.1'
match = re.search(r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}', ip)
# Or if you want to match it on it's own line.
# match = re.search(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', ip)
if match:
print "IP Address: %s" %(match.group)
else:
print "No IP Address"
使用正则表达式可以使数据匹配更轻松.
Regular expressions will make your life much easier when doing data matching.
这篇关于Python识别字符串中的IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!