Regex scenarios to Match IP Address with Optional Port in C# - Handling Edge Cases
Does anyone know how to I just started working with I've been struggling with this for a few days now and could really use some help... I'm trying to create a regex pattern in C# to match an IPv4 address that may optionally include a port number. My current regex looks like this: ```csharp string pattern = "^(\d{1,3}\.){3}\d{1,3}(:\d{1,5})?$"; ``` However, I'm working with issues where it sometimes fails to match valid IP addresses like `192.168.1.1:8080` but accepts others like `256.256.256.256` which is an invalid IP. I initially attempted to enforce the byte range for the octets but Iām struggling to construct a regex that accurately restricts the values to 0-255 for each octet. My regex also needs to ensure that if a port is provided, it should be in the range of 1-65535. I tried using this regex variation: ```csharp string pattern = "^(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?::([1-9][0-9]{0,4}|[1-5][0-9]{0,4}|[1-5][0-9]{0,4}|6[0-4][0-9]{0,4}|65[0-5][0-3][0-5]|655[0-2][0-9]|6553[0-5]))?$"; ``` But this one doesn't compile due to invalid quantifiers and does not match correctly. I'm using .NET 5.0, and I need this regex to work efficiently without important performance impact on large input strings. How can I properly construct this regex to ensure both the validity of the IP address and the port number while avoiding false positives? Any suggestions or improvements would be greatly appreciated! This is part of a larger API I'm building. I'm coming from a different tech stack and learning C#. Could someone point me to the right documentation? I'm working with C# in a Docker container on Windows 10. Could someone point me to the right documentation?