Home  >  Article  >  Backend Development  >  Python implementation to determine whether a string is a legal IP address

Python implementation to determine whether a string is a legal IP address

不言
不言Original
2018-06-04 16:13:584818browse

This article mainly introduces the python implementation to determine whether a string is a legal IP address. It has certain reference value. Now I share it with you. Friends in need can refer to it

A written test question that just ended, please post it briefly. The following is the specific implementation:

#!usr/bin/env python
#encoding:utf-8
'''
__Author__:沂水寒城
功能:判断一个字符串是否是合法IP地址
'''
import re
def judge_legal_ip(one_str):
  '''
  正则匹配方法
  判断一个字符串是否是合法IP地址
  '''
  compile_ip=re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$') 
  if compile_ip.match(one_str): 
    return True 
  else: 
    return False 
def judge_legal_ip2(one_str):
  '''
  简单的字符串判断
  '''
  if '.' not in one_str:
    return False
  elif one_str.count('.')!=3:
    return False
  else:
    flag=True
    one_list=one_str.split('.')
    for one in one_list:
      try:
        one_num=int(one)
        if one_num>=0 and one_num<=255:
          pass
        else:
          flag=False
      except:
        flag=False
    return flag
          
if __name__==&#39;__main__&#39;:
  ip_list=[&#39;&#39;,&#39;172.31.137.251&#39;,&#39;100.10.0.1000&#39;,&#39;1.1.1.1&#39;,&#39;12.23.13&#39;,&#39;aa.12.1.2&#39;,&#39;12345678&#39;,&#39;289043jdhjkbh&#39;]
  for one_str in ip_list:
    if judge_legal_ip(one_str): #正则方法
    #if judge_legal_ip2(one_str): #字符串方法
      print &#39;{0} is a legal ip address!&#39;.format(one_str)
    else:
      print &#39;{0} is not a legal ip address!&#39;.format(one_str)

The results are as follows:

is not a legal ip address! 
172.31.137.251 is a legal ip address! 
100.10.0.1000 is not a legal ip address! 
1.1.1.1 is a legal ip address! 
12.23.13 is not a legal ip address! 
aa.12.1.2 is not a legal ip address! 
12345678 is not a legal ip address! 
289043jdhjkbh is not a legal ip address!

Related recommendations:

Python implementation determines whether the array contains the specified Element methods

The above is the detailed content of Python implementation to determine whether a string is a legal IP address. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn