C#中不支持\K、(*SKIP)的邮箱掩码正则表达式替代方案
Great question! The regex you’re using leverages PCRE-specific features like \K and (*SKIP)(?!) that aren’t supported by .NET’s regex engine. Let’s walk through two solid approaches to replicate that email masking functionality in C#—one using a regex workaround, and a simpler non-regex method that’s often easier to maintain.
C# Regex Workaround Using Match Evaluator
Since we can’t rely on PCRE-specific syntax, we’ll use capture groups to isolate the parts of the email we want to keep, then use a MatchEvaluator to dynamically replace the middle sections with the correct number of * characters. This matches the behavior of your original regex:
using System; using System.Text.RegularExpressions; public class EmailMasker { public static string MaskEmailWithRegex(string email) { if (string.IsNullOrWhiteSpace(email)) return email; // Capture: [1] First 1-2 chars of username, [2] Remaining username chars, // [3] @ + first 1-2 domain chars, [4] Remaining domain chars before suffix, [5] Full domain suffix var emailRegex = new Regex(@"^(.{1,2})(.*?)(@.{1,2})(.*?)(\..+)$"); return emailRegex.Replace(email, match => { // Build masked sections with * matching the length of original hidden content string maskedUsernameMiddle = new string('*', match.Groups[2].Length); string maskedDomainMiddle = new string('*', match.Groups[4].Length); // Combine kept and masked parts return $"{match.Groups[1].Value}{maskedUsernameMiddle}{match.Groups[3].Value}{maskedDomainMiddle}{match.Groups[5].Value}"; }); } // Example usage public static void Main() { Console.WriteLine(MaskEmailWithRegex("abcdef@example.com")); // Output: ab****@ex********.com Console.WriteLine(MaskEmailWithRegex("a@b.com")); // Output: a*@b*.com Console.WriteLine(MaskEmailWithRegex("test@sub.domain.co.uk")); // Output: te**@su***********.co.uk } }
Simpler Non-Regex Approach
For most real-world scenarios, a manual string manipulation method is more readable and easier to adjust for edge cases (like usernames shorter than 2 characters or domains without a visible suffix). Here’s a straightforward implementation:
public static string MaskEmailWithoutRegex(string email) { if (string.IsNullOrWhiteSpace(email)) return email; // Split email into username and domain parts int atSymbolIndex = email.IndexOf('@'); if (atSymbolIndex == -1) return email; // Return original if it's not a valid email format string username = email.Substring(0, atSymbolIndex); string domain = email.Substring(atSymbolIndex + 1); // Mask username: keep first 2 chars, replace rest with * string maskedUsername = username.Length <= 2 ? username : username.Substring(0, 2) + new string('*', username.Length - 2); // Mask domain: keep first 2 chars of the prefix (before last .), replace rest with *, keep full suffix int lastDotIndex = domain.LastIndexOf('.'); string maskedDomain; if (lastDotIndex == -1) { // No suffix found, mask entire domain except first 2 chars maskedDomain = domain.Length <= 2 ? domain : domain.Substring(0, 2) + new string('*', domain.Length - 2); } else { string domainPrefix = domain.Substring(0, lastDotIndex); string domainSuffix = domain.Substring(lastDotIndex); string maskedPrefix = domainPrefix.Length <= 2 ? domainPrefix : domainPrefix.Substring(0, 2) + new string('*', domainPrefix.Length - 2); maskedDomain = maskedPrefix + domainSuffix; } return $"{maskedUsername}@{maskedDomain}"; }
This non-regex approach gives you explicit control over each part of the email, making it simpler to tweak if you need to adjust masking rules (e.g., keep 3 characters instead of 2, or mask the domain suffix differently).
内容的提问来源于stack exchange,提问作者Luis Antoni Del Águila Jacobo

