(JAVA) 電話、郵箱脫敏,帶脫敏規則

不多說,直接上代碼,拷走就能用:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PhoneOrEmailUtil {
	/**
	 * 	脫敏規則——手機號碼(手機號碼隱藏中間4位數)
	 * @Description: 
	 * @param telnum
	 * @return
	 * @ReturnType String
	 * @author: zzx
	 * @Created 2020年6月2日 上午10:25:10
	 */
	public static String phoneNum(String telnum){
		String rtnStr = telnum;
		if(isEmpty(rtnStr)||rtnStr.trim().length()<7){
			return rtnStr;
		}
		rtnStr = rtnStr.trim();
		// 校驗是否爲電話號碼
		String regExp = "^1\\d{10}$";
        Pattern p = Pattern.compile(regExp);  
        Matcher m = p.matcher(rtnStr);  
        if(m.matches()){// 若判斷爲固話
//        	rtnStr = replace(rtnStr,rtnStr.length()-3,"****");
        	rtnStr = replace(rtnStr,4,"****");
        }
        return rtnStr;
	}
	
	/**
	 * 	脫敏規則——郵箱 (@前三位)
	 * @Description: 
	 * @param str
	 * @return
	 * @ReturnType String
	 * @author: zzx
	 * @Created 2020年6月2日 上午10:25:10
	 */
	public static String emailNum(String str){
		String rtnStr = str;
		String regExp = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        Pattern p = Pattern.compile(regExp); 
        Matcher matcher = p.matcher(rtnStr);  
        boolean isMatched = matcher.matches(); 
		if(isMatched){
			int s =  rtnStr.indexOf("@");
			if(s >= 6) {
				return replace(rtnStr.trim(), s-3, "****");
			}else if(s >= 3 && s < 6) {
				return replace(rtnStr.trim(), s-1, "**");
			}else {
				return str;
			}
		}else{
			return rtnStr;
		}
	}
	
	/**
	 * 脫敏規則
	 * @Description: 
	 * @param str(需脫敏的字符串) 
	 * @param n(脫敏開始位)
	 * @param newChar(脫敏掩碼)
	 * @return
	 * @ReturnType String
	 * @author: zzx
	 * @Created 2020年6月2日 上午10:25:10
	 */
	public static String replace (String str,int n,String newChar){ 
		String s1=""; 
		String s2=""; 
		try{
			s1=str.substring(0,n-1); 
			s2=str.substring(n-1+newChar.length(),str.length());
			return s1+newChar+s2;
		}catch(Exception ex){ 			
			return str;
		} 
	}
	
	/**
	 * 判斷字符串是否爲null || 空字符串
	 * 
	 * @param param
	 * @return
	 */
	public static boolean isEmpty(String param) {
		return param == null || "".equals(param.trim());
	}
	public static String replaceChar(String str) {
		String rtnStr = str;
        if(!isEmpty(rtnStr)) {
        	String regExp = "^1\\d{10}$";
        	Pattern p = Pattern.compile(regExp);  
        	Matcher m = p.matcher(rtnStr);         	
        	
        	String regExp2 = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
            Pattern p2 = Pattern.compile(regExp2); 
            Matcher matcher2 = p2.matcher(rtnStr);  
            
        	if(m.matches()) {
        		rtnStr = phoneNum(str);
        	}else if(matcher2.matches()) {
        		rtnStr = emailNum(str);
        	}        	
        }
		return rtnStr;
	}
	public static void main(String args[]) {
		String str = "xxxxxxxxxxx";
		System.out.println(phoneNum(str));
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章