Skip to content

Instantly share code, notes, and snippets.

@roipeker
Created January 20, 2021 15:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save roipeker/6ebc2e4af18d354f1941c3f8cd0674ad to your computer and use it in GitHub Desktop.
Save roipeker/6ebc2e4af18d354f1941c3f8cd0674ad to your computer and use it in GitHub Desktop.
Mask Email RegExp for Dart
import 'dart:math';
void testMaskEmail() {
final emails = [
'a@example.com',
// output: a****a@example.com
'ab@example.com',
// output: a****b@example.com
'abc@example.com',
// output: a****c@example.com
'abcd@example.com',
// output: a****d@example.com
'abcde@example.com',
// output: a****e@example.com
'abcdef@example.com',
// output: a****f@example.com
'abcdefg@example.com',
// output: a*****g@example.com <- 5-asterisk-fill
'Ф@example.com',
// output: Ф****Ф@example.com
'ФѰ@example.com',
// output: Ф****Ѱ@example.com
'ФѰД@example.com',
// output: Ф****Д@example.com
'ФѰДӐӘӔӺ@example.com',
// output: Ф*****Ӻ@example.com <- 5-asterisk-fill
'"a@tricky@one"@example.com',
// output: "************"@example.com <- multiple @ in a valid email: no problem
];
emails.forEach((email) {
print("Email: $email - mask: " + maskEmail(email, 4, '*'));
});
}
final _emailMaskRegExp = RegExp('^(.)(.*?)([^@]?)(?=@[^@]+\$)');
String maskEmail(String input, [int minFill = 4, String fillChar = '*']) {
minFill ??= 4;
fillChar ??= '*';
return input.replaceFirstMapped(_emailMaskRegExp, (m) {
var start = m.group(1);
var middle = fillChar * max(minFill, m.group(2).length);
var end = m.groupCount >= 3 ? m.group(3) : start;
return start + middle + end;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment