正则表达式查找除 IP 地址以外的所有 ip 地址以 172 开头 [英] Regex for find All ip address except IP address starts with 172

查看:39
本文介绍了正则表达式查找除 IP 地址以外的所有 ip 地址以 172 开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让正则表达式找到不以 172.0.0.0 开头的 IP 地址.

我写了一些正则表达式 ^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$ 查找所有 IP 地址.

解决方案

. 在正则表达式中是匹配所有内容的字符.要在此上下文中使用它,您必须将其转义.

还要将其限制为仅以 172 开头的 IP 地址,只需将其硬编码到您的正则表达式中,如下所示:

^172\.\d{1,3}\.\d{1,3}.\d{1,3}$

<小时>

小心一点,因为这可能匹配多个 ip 地址 - 例如 400.660.226.602 将被捕获 - 即使真实的 IP4 地址不包含高于 255 的数字代码>.也许这不会影响您的用例 - 但这是需要记住的.

<小时>

根据下面的评论,如果您在文档中的任何位置搜索 IP 地址,而不是在它们自己的行中,请使用 \b 而不是 ^ 和 <代码>$

\b(?!172)\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\b

Debuggex 演示

例如,这将匹配日志格式,其中包含消息中的 ip 地址,而不是它自己的行.

<块引用>

[10:01:22] 来自 10.14.242.211 的连接建立.

I want regex to find IP address which not starts with 172.0.0.0.

I have written some regex ^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$ which finds all ip address.

解决方案

. in a regex is character that matches everything. To use it in this context, you must escape it.

Also to limit it to just ip addresses that start with 172, simply hardcode it into your regex like so:

^172\.\d{1,3}\.\d{1,3}.\d{1,3}$

Debuggex Demo

You could then use this to filter out any matches already made.


Alternatively, if you're not starting with a list of ip addresses, you could use a negative look-ahead to grab them all straight away.

^(?!172)\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}$

Debuggex Demo


Be a little careful in that this may match more than ip addresses - for example 400.660.226.602 would be captured - even though real IP4 addresses do not contain numbers higher than 255. Perhaps this won't affect your use case - but it's something to remember.


As per the comments below, if you are searching for IP addresses anywhere in the document, rather than on their own line, use \b instead of ^ and $

\b(?!172)\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\b

Debuggex Demo

This would match log formats for example, which contain an ip address within the message rather than on it's own line.

[10:01:22] Connection from 10.14.242.211 established.

这篇关于正则表达式查找除 IP 地址以外的所有 ip 地址以 172 开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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