如何编写 IP 的正则表达式并排除特定 IP

How to write a regex of IP and exclude specific IP

我需要验证应遵循 IPv4 代理模式的字符串。 但是 0.0.0.0(...) 是不允许的

0.0.0.0/23(not match)
0.0.0.0/0(not match)
12.2.3.4/23(match)
13.2.3.53(match)

目前我有匹配的正则表达式(IP 和 IP 代理)

(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/\d+)?

但是我怎么能排除 0.0.0.0 或 0.0.0.0/...

使用gnu grep你可以使用负前瞻:

grep -P '^(?!0\.0\.0\.0/)(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/\d+)?' file
12.2.3.4/23(match)
13.2.3.53(match)

否则,您可以使用 awk 排除 0.0.0.0,如下所示:

awk -F/ ' != "0.0.0.0"' file

12.2.3.4/23(match)
13.2.3.53(match)