正则表达式:如何从字符串中仅提取第一个 IP 地址(在 Python 中) [英] Regex: how to extract only first IP address from string (in Python)

查看:39
本文介绍了正则表达式:如何从字符串中仅提取第一个 IP 地址(在 Python 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下字符串(或类似字符串,其中一些可能包含多个 IP 地址):

 from mail2.oknotify2.com (mail2.oknotify2.com. [208.83.243.70]) by mx.google.com,ESMTP id dp5si2596299pdb.170.2015.06.03.14.12.03

我希望在 Python 中提取第一个也是唯一的第一个 IP 地址.在 nregex.com 上尝试时,第一次尝试使用类似 ([0-9]{2,}\.){3}([0-9]{2,}){1} 的东西, 看起来几乎 OK,可以很好地匹配 IP 地址,但也可以匹配大致类似于 IP 地址 (170.2015.06.03.14.12.03) 的其他子字符串.当相同的模式传递给 re.compile/re.findall 时,结果是:

[(u'243.', u'70'), (u'06.', u'03')]

很明显正则表达式不好.我怎样才能改进它,使它更整洁并捕获所有 IPV4 地址,我怎样才能使它只匹配第一个?

非常感谢.

解决方案

使用 re.search 和以下模式:

<预><代码>>>>s = '来自 mail2.oknotify2.com (mail2.oknotify2.com. [208.83.243.70]) 来自 mx.google.com,ESMTP id 为 dp5si2596299pdb.170.2015.06.03.14.12.03'>>>进口重新>>>re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', s).group()'208.83.243.70'

Given the following string (or similar strings, some of which may contain more than one IP address):

from mail2.oknotify2.com (mail2.oknotify2.com. [208.83.243.70]) by mx.google.com with ESMTP id dp5si2596299pdb.170.2015.06.03.14.12.03

I wish to extract the first and only the first IP address, in Python. A first attempt with something like ([0-9]{2,}\.){3}([0-9]{2,}){1} when tried out on nregex.com, looks almost OK, matching the IP address fine, but also matches the other substring which roughly resembles an IP address (170.2015.06.03.14.12.03). When the same pattern is passed to re.compile/re.findall though, the result is:

[(u'243.', u'70'), (u'06.', u'03')]

So clearly the regex is no good. How can I improve it so that it's neater and catches all IPV4 address, and how can I make it such that it only matches the first?

Many thanks.

解决方案

Use re.search with the following pattern:

>>> s = 'from mail2.oknotify2.com (mail2.oknotify2.com. [208.83.243.70]) by mx.google.com with ESMTP id dp5si2596299pdb.170.2015.06.03.14.12.03'
>>> import re
>>> re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', s).group()
'208.83.243.70'

这篇关于正则表达式:如何从字符串中仅提取第一个 IP 地址(在 Python 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆