Partager via


Regular Expressions and IP addresses (ipv4 and IPv6)

Over the last year or so I have been writing automation that uses IPv4 and IPv6 addresses.  In the beginning I had to dig up and make some regular expressions for verifying that a given value was a valid IPv4 or IPv6 address. 

The ones I came up with are (in VB.net)

Const strIPv4Pattern as string = "\A(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\z" 'IPv4 Address Regex pattern (x.x.x.x)

Const strIPv6Pattern as string = "\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\z"

Const strIPv6Pattern_HEXCompressed as string = "\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\z"

Const StrIPv6Pattern_6Hex4Dec as string = "\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\z"

Const StrIPv6Pattern_Hex4DecCompressed as string = "\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\z"

Now because an IPv6 address can take a few forms we have 4 different expressions for IPv6.  If someone finds a bug in one of these please let me know.  Because RegExp is something that I am not good at. 

Hope these will help some one.

Comments

  • Anonymous
    January 25, 2005
    Hi there, I have to convert the following java regex to .Net regex, this one does not seem to be working in .Net.

    <RegexPattern pattern="^150.215.([12]d{2}|[13-9]d|2[2-9]|[1-9]).d{1,3}$" />


    Please email me at leokapil2000@hotmail.com

    Thanks,
    leo