Regex Not Capturing Dotted Decimal IP Addresses in C# with Optional Port Numbers
I'm working on a C# application where I need to extract IP addresses in dotted decimal format from a log file. The IPs can optionally have port numbers following them, like `192.168.1.1:8080`. However, my regex pattern seems to unexpected result in some cases. I'm using the following regex pattern: ```csharp string pattern = "(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d{1,5}))?"; ``` While this captures most cases, it doesn't seem to handle scenarios where the IP address is at the end of a line or followed by certain punctuation. For example, it fails to match `192.168.1.1:` or `192.168.1.1,` and I get an empty result instead of the expected match. I tried modifying the regex to include optional trailing characters, but that only complicates things further and doesn't yield the right results. Here's a snippet of the code I use to extract the IPs: ```csharp Regex regex = new Regex(pattern); MatchCollection matches = regex.Matches(logContent); foreach (Match match in matches) { Console.WriteLine(match.Value); } ``` The log content has several entries like: ``` Connection established from 192.168.1.1: Failed login attempt from 192.168.1.2, Last connection from 10.0.0.5:8080. ``` I'm using .NET 5.0 and would appreciate any help on refining the regex to correctly capture those edge cases. I've also considered using `IPAddress.TryParse` after matching, but Iām looking for a regex solution first. Any suggestions?