2019年8月1日 星期四

[java]地址隱碼

/**
* 地址隱碼
 * @param address
* @return
*/
public static String addressToMaskFormat(final String address)
{
if (StringUtils.isEmpty(address))
{
return "";
}
//郵政信箱不隱碼:臺北北門郵局第○○號信箱
if (address.contains("信箱"))
{
return address;
}
//地址自路段後全隱
final String zoneValue = address.replaceAll("^(.*[鄉|鎮|市|區])(.*)$", "$1"); //鄉鎮市區資訊
final String fullRoadValue = address.replaceAll("^(.*[鄉|鎮|市|區])(.*)$", "$2"); //路段之後的資訊
System.out.println("zoneValue="+zoneValue);
System.out.println("fullRoadValue="+fullRoadValue);
if (StringUtils.isNotEmpty(zoneValue) && StringUtils.isNotEmpty(fullRoadValue))
{
String laneValue = fullRoadValue;//預設巷弄號樓資訊
String roadValue = fullRoadValue.replaceAll("^(.*[路|段|街])(.*)$", "$1");//截取正常路段名資訊
if (StringUtils.isNotEmpty(roadValue) && !roadValue.equals(laneValue))
{
laneValue = fullRoadValue.replaceAll("^(.*[路|段|街])(.*)$", "$2"); //有正常路段名資訊 XX路 XX段 XX街 時,再截取巷弄號樓資訊
}else{
roadValue="";
}

final String visibleLaneValue = laneValue.replaceAll("([0-9|0|1|2|3|4|5|6|7|8|9|一|二|三|四|五|六|七|八|九|十]*[巷|弄|號].*)$", "");
final String hiddenLaneValue = laneValue.replaceAll(visibleLaneValue, "");

if (StringUtils.isNotEmpty(hiddenLaneValue) && hiddenLaneValue.length() > 1)
{
//hiddenLaneValue不超過1碼時,代表地址不全,全隱
return zoneValue + roadValue + visibleLaneValue + addStar("", hiddenLaneValue.length());
}
}

//上面地址格式不對時
if (address.length() > 10)
{
final String hiddenValue = address.replaceAll("^(.{10})(.*)$", "$2");
return address.replaceAll(hiddenValue, addStar("", hiddenValue.length()));
}

//若地址不足10碼,則直接出******
return "******";

}

/**
*
* @param str 欲格式化的字串
* @param len  格式化長度
* @param fillchar 想補齊的字元
* @return
*/
public static String addStar(final String str, final int len)
{
final String fillchar = "*";
final StringBuffer sb = new StringBuffer();
if (str == null)
{
for (int i = 0; i < len; i++)
{
sb.append(fillchar);
}
}
else
{
final int strLen = str.length();
if (strLen < len)
{
for (int i = 0; i < (len - strLen); i++)
{
sb.append(fillchar);
}
return str + sb.toString();
}
else
{
if (str.length() == len)
{
return str;
}
else
{
return str.substring(0, len);
}
}
}
return sb.toString();
}
^