我有以下字符串:
text = '10.0.0.1.1 but 127.0.0.256 1.1.1.1'
我想返回有效的IP地址,所以它应该只返回1.1.1.1
自从这里256
高于255
并且第一个IP编号过多。
到目前为止,我有以下内容,但它不适用于0-255
要求。
text = "10.0.0.1.1 but 127.0.0.256 1.1.1.1"
l = []
import re
for word in text.split(" "):
if word.count(".") == 3:
l = re.findall(r"[\d{1,3}]+\.[\d{1,3}]+\.[\d{1,3}]+\.[\d{1,3}]+",word)
下面是一个 Python 正则表达式,它可以很好地从字符串中获取有效的 IPv4 IP 地址:
import re
reValidIPv4 = re.compile(r"""
# Match a valid IPv4 in the wild.
(?: # Group two start-of-IP assertions.
^ # Either the start of a line,
| (?<=\s) # or preceeded by whitespace.
) # Group two start-of-IP assertions.
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # First number in range 0-255
(?: # Exactly 3 additional numbers.
\. # Numbers separated by dot.
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # Number in range 0-255 .
){3} # Exactly 3 additional numbers.
(?=$|\s) # End IP on whitespace or EOL.
""", re.VERBOSE | re.MULTILINE)
text = "10.0.0.1.1 but 127.0.0.256 1.1.1.1"
l = reValidIPv4.findall(text)
print(l)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)