这样也不行#!/usr/bin/env python
#coding=utf-8
import re
pattern = r'((25[0-5]|2[0-4]\d|1\d{2}|\d{1,2})\.){3}(25[0-5]|2[0-4]\d|1\d{2}|\d{1,2})'
print(re.search(pattern, 'abc192.168.1.152efg'))
print(re.search(pattern, '0.0.0.0'))
print(re.search(pattern, '255.255.255.255'))
print(re.search(pattern, '10.99.100.149'))
print(re.search(pattern, '253.250.240.249'))
print(re.search(pattern, '256.250.240.249')) # error
print(re.search(pattern, '253.256.240.249'))
print(re.search(pattern, '253.250.240.259')) # error
我感觉用正则表达式无法完成这个任务
简单一点
先用正则表达式匹配一个ip格式的文本,如何再用代码来判断这个ip是不是合法的ip##!/usr/bin/env python
#coding=utf-8
import re
def search_ip(text):
result = re.search(r'((\d{1,3})\.){3}(\d{1,3})', text)
if not result: return None
for i in result.string.split('.'):
if int(i) < 0 or int(i) > 255: return None
return result
print(search_ip('0.0.0.0'))
print(search_ip('255.255.255.255'))
print(search_ip('10.99.100.149'))
print(search_ip('253.250.240.249'))
print(search_ip('256.250.240.249'))
print(search_ip('253.256.240.249'))
print(search_ip('253.250.240.259'))
print(search_ip('abcefg'))
|