CodexBloom - Programming Q&A Platform

Regex Failing to Capture IPv6 Addresses Properly in C# using System.Text.RegularExpressions

👀 Views: 68 💬 Answers: 1 📅 Created: 2025-06-13
regex ipv6 csharp C#

Quick question that's been bugging me - I'm working on a personal project and I'm working on a C# application that needs to validate and capture IPv6 addresses from various text inputs. I've used the `System.Text.RegularExpressions` namespace and created a regex pattern, but it's not capturing all valid IPv6 formats correctly. Here’s my regex pattern: ```csharp string pattern = "([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4}|:)|([0-9a-fA-F]{1,4}:){1,7}:|::([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(?!$)|$)){4}|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(?!$)|$)){4})|([0-9a-fA-F]{1,4}:){1,5}:((25[0-5]|(2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(?!$)|$)){4}))"; ``` Despite the complexity of the regex, I find it fails to match certain valid addresses, especially those with consecutive zero blocks like `2001:0db8::1` or mixed formats like `::ffff:192.168.1.1`. I’ve tested this pattern using `Regex.Match(input)` but it returns `false` for some inputs that should be valid. The expected behavior is to have a match return true for valid IPv6 addresses. I’ve also tried simplifying the regex, but then I miss out on valid formats. Here’s an example of how I’m using it in my code: ```csharp using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "2001:0db8::1"; var match = Regex.Match(input, pattern); Console.WriteLine(match.Success ? "Valid IPv6" : "Invalid IPv6"); } } ``` What am I missing here? Is there a better regex pattern I should be using, or is there a specific edge case I’ve overlooked? Any help would be appreciated! I'm working on a application that needs to handle this. Any ideas what could be causing this? I'd really appreciate any guidance on this.