Created
August 12, 2012 13:48
-
-
Save vivisidea/3331896 to your computer and use it in GitHub Desktop.
使用星号遮挡email地址, masking email address using stars * :)
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
/** | |
* 遮掩指定的位置 | |
* @param array | |
* @param positions | |
* @return | |
*/ | |
private static String mask(char[] array, int[] positions){ | |
for(int position : positions){ | |
array[position] = '*'; | |
} | |
return new String(array); | |
} | |
/** | |
* 0 | |
* 0* | |
* 0*2 | |
* 0**3 | |
* 01**4 | |
* 01**45 | |
* 01***56 | |
* 01***567 | |
* 012***678 | |
* 012****789 | |
* 0123****890 | |
* >=12 位的只显示前后4位 | |
* | |
* 用星号遮挡邮件地址 | |
* @param email | |
* @return | |
*/ | |
public static String maskEmail(String email){ | |
if(!EmailValidator.getInstance().isValid(email)){ | |
logger.warn(String.format("错误的email格式:%s", email)); | |
return email; | |
} | |
int index = email.indexOf('@'); | |
String prefix = email.substring(0, index); | |
String suffix = email.substring(index); | |
int length = prefix.length(); | |
char[] array = prefix.toCharArray(); | |
String output = null; | |
switch(length){ // 虽然挺土的,但很实用... simple & stupid | |
case 1: output = email; break; | |
case 2: output = mask(array, new int[]{1})+suffix; break; | |
case 3: output = mask(array, new int[]{1,2})+suffix; break; | |
case 4: output = mask(array, new int[]{1,2})+suffix; break; | |
case 5: output = mask(array, new int[]{2,3})+suffix; break; | |
case 6: output = mask(array, new int[]{2,3,4})+suffix; break; | |
case 7: output = mask(array, new int[]{2,3,4})+suffix; break; | |
case 8: output = mask(array, new int[]{2,3,4})+suffix; break; | |
case 9: output = mask(array, new int[]{3,4,5})+suffix; break; | |
case 10: output = mask(array, new int[]{3,4,5,6})+suffix; break; | |
case 11: output = mask(array, new int[]{4,5,6,7})+suffix; break; | |
default: | |
for(int i = 4; i < length - 4; i++){ | |
array[i] = '*'; | |
} | |
output = new String(array)+suffix; | |
break; | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment