假设我有 3 个字符串:
str1 = 'Hello my name is Ben and my IP address is 127.1.1.1'
str2 = 'Hello my name is Folks and my IP address is 1.2.3.4.5'
str3 = 'Hello all, ip addresses: 1.2.3.4.5, 127.1.2.1, 127.2.1.2'
我想得到以下输出:
find_ip(str1) #['127.1.1.1']
find_ip(str2) #[]
find_ip(str2) #['127.1.2.1', '127.2.1.2']
- 标准:
- IM 地址格式为“x.x.x.x”
- 正则表达式应该是1组。
- 位数并不重要(111.111.111.111)即可。
P.Sthis StackOverflow post的解决方案不回答这个问题。
最佳答案
以下正则表达式匹配从 0.0.0.0
到 255.255.255.255
的 IP,前后不带句点或数字:
(?<![\.\d])(?:[0-9]\.|1\d?\d?\.|2[0-5]?[0-5]?\.){3}(?:[0-9]|1\d?\d?|2[0-5]?[0-5]?)(?![\.\d])
演示:https://regex101.com/r/UUCywc/3
编辑:避免匹配以负数作为第一位的 IP(例如 -127.2.1.2
),并允许像 001.001.001.001
这样的 IP,然后使用:
(?<![-\.\d])(?:0{0,2}?[0-9]\.|1\d?\d?\.|2[0-5]?[0-5]?\.){3}(?:0{0,2}?[0-9]|1\d?\d?|2[0-5]?[0-5]?)(?![\.\d])
演示:https://regex101.com/r/UUCywc/6
完整的Python实现:
import re
str1 = 'Hello my name is Ben and my IP address is 127.1.1.1'
str2 = 'Hello my name is Folks and my IP address is 1.2.3.4.5'
str3 = 'Hello all, ip addresses: 1.2.3.4.5, 127.1.2.1, 127.2.1.2'
def find_ip(test_str):
regex = re.compile(r"(?<![-\.\d])(?:0{0,2}?[0-9]\.|1\d?\d?\.|2[0-5]?[0-5]?\.){3}(?:0{0,2}?[0-9]|1\d?\d?|2[0-5]?[0-5]?)(?![\.\d])")
return regex.findall(test_str)
print(find_ip(str1)) #['127.1.1.1']
print(find_ip(str2)) #[]
print(find_ip(str3)) #['127.1.2.1', '127.2.1.2']
关于python - 用于匹配 IPv4 地址的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55928637/