-
-
Save kaaaaai/cab965d547f51923323c6fdeae59b603 to your computer and use it in GitHub Desktop.
Mask Email RegExp for Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:math'; | |
void testMaskEmail() { | |
final emails = [ | |
'[email protected]', | |
// output: a****[email protected] | |
'[email protected]', | |
// output: a****[email protected] | |
'[email protected]', | |
// output: a****[email protected] | |
'[email protected]', | |
// output: a****[email protected] | |
'[email protected]', | |
// output: a****[email protected] | |
'[email protected]', | |
// output: a****[email protected] | |
'[email protected]', | |
// output: a*****[email protected] <- 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