正则匹配ipv6地址+测试用例

警告
本文最后更新于 2022-08-05 20:46,文中内容可能已过时。

从logstash grok里扒出来的 https://raw.githubusercontent.com/logstash-plugins/logstash-patterns-core/main/patterns/legacy/grok-patterns

1
((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-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}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9A-Fa-f]{1,4}){1,7})|(?:(:[0-9A-Fa-f]{1,4}){0,5}:(?:(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))

测试用例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# TEST: 1:2:3:4:5:6:7:8
# TEST: 1::                              1:2:3:4:5:6:7::
# TEST: 1::8             1:2:3:4:5:6::8  1:2:3:4:5:6::8
# TEST: 1::7:8           1:2:3:4:5::7:8  1:2:3:4:5::8
# TEST: 1::6:7:8         1:2:3:4::6:7:8  1:2:3:4::8
# TEST: 1::5:6:7:8       1:2:3::5:6:7:8  1:2:3::8
# TEST: 1::4:5:6:7:8     1:2::4:5:6:7:8  1:2::8
# TEST: 1::3:4:5:6:7:8   1::3:4:5:6:7:8  1::8
# TEST: ::2:3:4:5:6:7:8  ::2:3:4:5:6:7:8 ::8       ::     
# TEST: fe08::7:8%eth0      fe08::7:8%1
# TEST: ::255.255.255.255   ::ffff:255.255.255.255  ::ffff:0:255.255.255.255
# TEST: 2001:db8:3:4::192.0.2.33  64:ff9b::192.0.2.33
# TEST: fe80::7:8%eth0   fe80::7:8%1
# TEST: ::255.255.255.255   ::ffff:255.255.255.255  ::ffff:0:255.255.255.255
# TEST: 2001:db8:3:4::192.0.2.33  64:ff9b::192.0.2.33

参考

https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses https://gist.github.com/syzdek/6086792

请我喝杯水
SoulChild 微信号 微信号
SoulChild 微信打赏 微信打赏
0%