Skip to content

Instantly share code, notes, and snippets.

@edbond
Last active March 19, 2021 14:28
Show Gist options
  • Save edbond/b5637089d9c5f17b9317011f755937d8 to your computer and use it in GitHub Desktop.
Save edbond/b5637089d9c5f17b9317011f755937d8 to your computer and use it in GitHub Desktop.
Obfuscate emails
String safeEmail(String email) {
final match = RegExp(r"(?<a>.?)(?<x>[^@]*)@(?<b>.)(?<y>.+?)(?<c>\..+)").firstMatch(email);
if (match == null) {
return email.replaceAll(RegExp(r"."), "*");
}
var sb = StringBuffer();
sb.write(match.namedGroup("a"));
sb.write(List.filled(match.namedGroup("x")?.length ?? 1, "*").join(""));
sb.write("@");
sb.write(match.namedGroup("b"));
sb.write(List.filled(match.namedGroup("y")?.length ?? 1, "*").join(""));
sb.write(match.namedGroup("c"));
return sb.toString();
}
void main() {
final List<String> emails = [
"john.test@gmail.com",
"test@gmail.com",
"test@mail.ru",
"testmail.ru",
];
for (var email in emails) {
print("${email} => ${safeEmail(email)}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment