CodexBloom - Programming Q&A Platform

Regex Not Capturing Multiple Email Variants in C# - Unexpected Matches and Missing Cases

👀 Views: 94 💬 Answers: 1 📅 Created: 2025-06-23
regex c# email-validation C#

I'm upgrading from an older version and I'm experimenting with This might be a silly question, but I'm trying to use regex in C# to validate and capture different email formats, including those with subdomains and '+' aliasing..... My current regex pattern is as follows: ```csharp string pattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"; ``` However, I noticed that while it correctly matches simple email addresses, it fails to capture variations like `user+alias@example.com` or `user.name@subdomain.example.com`. When I test it against a list of emails, I get unexpected results, such as missing valid emails and false positives like `user@@example.com`. I also tried modifying the pattern to: ```csharp string pattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"; ``` But this didn’t resolve the scenario. I'm using .NET 5, and I've enabled RegexOptions.IgnoreCase. I've also checked that the input is correctly trimmed and valid before matching. Is there a more robust regex pattern that can account for these cases? How can I fix the unexpected behavior I'm working with? Any suggestions would be greatly appreciated! This is part of a larger API I'm building. For context: I'm using C# on Linux. For context: I'm using C# on Ubuntu 22.04. How would you solve this? This is my first time working with C# latest.