2 回答
TA贡献1798条经验 获得超3个赞
如果您的地址始终在一行的末尾,请在该行上定位:
ip_at_end = re.compile(r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', re.MULTILINE)
此正则表达式仅匹配行尾的点分四边形(4组数字,中间有点)。
演示:
>>> import re
>>> ip_at_end = re.compile(r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', re.MULTILINE)
>>> example = '''\
... Only addresses on the end of a line match: 123.241.0.15
... Anything else doesn't: 124.76.67.3, even other addresses.
... Anything that is less than a dotted quad also fails, so 1.1.4
... does not match but 1.2.3.4
... will.
... '''
>>> ip_at_end.findall(example)
['123.241.0.15', '1.2.3.4']
TA贡献1810条经验 获得超4个赞
描述
这将匹配并验证ipv4地址,并确保各个字节在0-255的范围内
(?:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
免责声明
是的,我意识到OP要求使用Python解决方案。仅包含此PHP解决方案以说明该表达式的工作原理
PHP的例子
<?php
$sourcestring="this is a valid ip 12.34.56.78
this is not valid ip 12.34.567.89";
preg_match_all('/(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/i',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
$matches Array:
(
[0] => Array
(
[0] => 12.34.56.7
)
)
添加回答
举报