如何在Go中使用正则表达式排除特定的IPv4地址?

huangapple go评论75阅读模式
英文:

How to exclude particular IPV4 addresses using regex in Go?

问题

我能够在JavaScript中使用负向先行断言来排除匹配特定的IP地址,比如127.0.0.1,但是我无法在Go中的微服务中使用相同的方法。

这是我在JavaScript中使用的正则表达式:

^(?!127\.0\.0\.1)(([1-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-1][0-9])|(22[0-3]))\.(((([0-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\.){2})(([1-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-4][0-9])|(25[0-5]))$
英文:

I am able to use negative lookahead in Javascript to not match certain IPs like 127.0.0.1 but I am unable to use the same for my microservice that runs in Go.

This is the regex I use in Javascript -

^(?!127\.0\.0\.1)(([1-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-1][0-9])|(22[0-3]))\.(((([0-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\.){2})(([1-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-4][0-9])|(25[0-5]))$

答案1

得分: 1

负向预查在Go的正则表达式中不受支持。请参考这个问题:https://stackoverflow.com/questions/26771592/negative-look-ahead-in-go-regular-expressions

可能需要考虑使用cidranger包。

英文:

Negative lookahead is not support in Go's regular expressions. See the question, https://stackoverflow.com/questions/26771592/negative-look-ahead-in-go-regular-expressions

Might want to look at using the package cidranger instead.

huangapple
  • 本文由 发表于 2022年2月8日 07:30:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/71026744.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定