RegExLib.com - The first Regular Expression Library on the Web!

Please support RegExLib Sponsors

Sponsors

Regular Expression Details

Title Test Find IPv6 (and IPv4) Address match with optional Port Number
Expression
(^|\s|(\[))(::)?([a-f\d]{1,4}::?){0,7}(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?=(?(2)\]|($|\s|(?(3)($|\s)|(?(4)($|\s)|:\d)))))|((?(3)[a-f\d]{1,4})|(?(4)[a-f\d]{1,4}))(?=(?(2)\]|($|\s))))(?(2)\])(:\d{1,5})?
Description
Too complex for a short explanation. It doesn't check for valid IP ranges and it also doesn't obey the rule, that a double colon in IPv6 only can exist once in the address notation. The optional port match at the end can be omitted. The RegEx has been constructed the way, that if an explicit identification fails, the complete match fails. For example someone write "My adress:2001::1234" the match will fail 'cos of the leading colon, even though it's an valid IPv6 address. A "My adress: 2001::1234" or "My adress:[2001::1234]" will work. Beware, that the RegEx is build for case-insensitive usage and no whitespaces are allowed inside the address. If you want to embed it into a larger RegEx, take into account to adjust the conditional matches wich refers to (?(2) -> (\[) inside (^|\s|(\[)) and (?(3) -> (::)? and (?(4) -> ([a-f\d]{1,4}::?) Works not perfectly, but I'm currently out of time.
Matches
::ffff:21:7.8.9.221 | 2001:0db8:85a3:08d3:1319:8a2e:0370:7344 | ::8a2e:0:0370:7344 | 2001:0db8:85a3:08d3:1319:8a2e:100.22.44.55 | 2001:0db8::8a2e:100.22.44.55 | ::100.22.44.55 | 100.22.44.55 | 100.22.44.55:80 | [::100.22.44.55]:8080 | [20ff::100.22.44.55]:8080
Non-Matches
20ff::100.22.44.55:8080 | ::8a2e:0:0370:7344.4 | 2001:0db8::8a2e:100.22.44.55:8080 | 2001:idb8::111:7.8.9.111 | 2001::100.a2.44.55 | :2001::100.22.44.55 | ffff:: (has to be fixed, 'cos a valid address)
Author Rating: Not yet rated. Gerry
Source
Your Rating
Bad Good

Enter New Comment

Title

Name

Comment

Spammers suck - we apologize. Please enter the text shown below to enable your comment (not case sensitive - try as many times as you need to if the first ones are too hard):

Existing User Comments

Copyright © 2001-2025, RegexAdvice.com | ASP.NET Tutorials