python - 用于匹配 IPv4 地址的正则表达式

标签 python regex python-3.x

假设我有 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']
  1. 标准:
    • IM 地址格式为“x.x.x.x”
    • 正则表达式应该是1组
    • 位数并不重要(111.111.111.111)即可。

P.Sthis StackOverflow post的解决方案回答这个问题。

最佳答案

以下正则表达式匹配从 0.0.0.0255.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/

相关文章:

python-3.x - Mypy 提示明显的 bool 表达式违反了 [no-any-return] 规则

python - 不明白这个 : n, S = map(int, input().split()) 的含义(动态规划中)

java - 如何使用正则表达式从 url 中的单词后获取数字

java - 具有嵌套分组的复杂 Java 正则表达式

python - 如何在 Windows 上配置 Tor 代理?

python - 为什么从字典中删除负值的代码不起作用?

python - 偶数的位数应该是偶数

python - 20newsgroup 数据集上的增强频率。TypeError : 'int' object is not iterable

python - Matplotlib 动画 : vertical cursor line through subplots

python - 如何匹配字符后面出现的字符串(如果存在),否则不应匹配任何内容