Python中解析IP的正则表达式

2024-10-01 13:43:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为Bind9服务器编写一个任务脚本。目标是让用户按以下格式输入IP地址:

192.168.90.150

然后,我希望Python获取该IP地址,并将其分为4个不同的组,分为4个不同的变量

^{pr2}$

我认为“行业标准”的方法是使用正则表达式。我尝试使用以下搜索字符串来识别由句点分隔的1-3个数字字符组成的分组。下面的方法不起作用。在

ipaddy = raw_input('Enter IP address: ')

failsearch1 = re.search(r'\d+\.')
failsearch2 = re.search(r'\d\.')
failsearch3 = re.search(r'(\d)+\.')

for x in ipaddy:
    a = search.failsearch1(x)
    b = search.failsearch2(x)
    c = search.failsearch3(x)
    if a or b or c:
        print('Search found')

上面代码的输出为空。在

我还尝试了这些搜索字符串的其他几种变体。有人知道我如何根据句点的间隔将一个典型的IP地址(192.168.10.10)分成4个不同的分组吗?在

如有任何建议,将不胜感激。谢谢。在


Tags: or方法字符串用户re服务器脚本目标
3条回答

您可以使用内置str函数。在

try:
    first, second, third, fourth = [int(s) for s in some_text.split('.')]
except ValueError as e:
    print 'Not 4 integers delimited by .'
if not all (0 <= i <= 254 for i in (first, second, third, fourth)):
    print 'Syntax valid, but out of range value: {} in "{}"'.format(i, some_text)

验证: How to validate IP address in Python?

+加

first, second, third, fourth = str(ipaddy).split('.')

如果您有理由确定输入将是虚线形式的IPv4,则甚至不需要正则表达式:

assert possible_ip.count(".") == 3
ip_parts = possible_ip.split(".")
ip_parts = [int(part) for part in ip_parts]
first, second, third, fourth = ip_parts

相关问题 更多 >