티스토리 뷰

private static final String MOBILE_PATTERN = "^(\\d{3})-?(\\d{3,4})-?(\\d{4})$";

@Test
public void mobileMaskingTest() {
// 휴대폰번호 형식
String mobile1 = "010-1234-5678";
String mobile2 = "01012345678";

System.out.println("휴대전화 : " + mobile(mobile1));
System.out.println("휴대전화 : " + mobile(mobile2));
}
public String mobile(String mobile) {
String replaceString = mobile;

Matcher matcher = Pattern.compile(MOBILE_PATTERN).matcher(mobile);

if(matcher.matches()) {
replaceString = "";

boolean isHyphen = false;
if(mobile.indexOf("-") > -1) {
isHyphen = true;
}

for(int i=1;i<=matcher.groupCount();i++) {
String replaceTarget = matcher.group(i);
if(i == 2) {
char[] c = new char[replaceTarget.length()];
Arrays.fill(c, '*');

replaceString = replaceString + String.valueOf(c);
} else {
replaceString = replaceString + replaceTarget;
}

if(isHyphen && i < matcher.groupCount()) {
replaceString = replaceString + "-";
}
}
}
return replaceString;
}


결과


휴대전화 : 010-****-5678

휴대전화 : 010****5678


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함