java
java 전화번호 형식 변환
jeongyj
2021. 6. 4. 14:03
서비스를 개발하다보면 전화번호를 다룰때가 많습니다.
집전화나 휴대폰전화 형식이 조금씩 다르고 사용자가 임의로 입력하게되면 그 형식이 또 다를수 있습니다.
그래서 보통 DB에 저장시에는 숫자만 저장하고 보여줄 때 형식에 맞게 보여줍니다.
그 형식에 맞게 보여주는 코드를 공유해봅니다.
public class FormatUtil {
public static String phone(String src) {
if (src == null) {
return "";
}
if (src.length() == 8) {
return src.replaceFirst("^([0-9]{4})([0-9]{4})$", "$1-$2");
} else if (src.length() == 12) {
return src.replaceFirst("(^[0-9]{4})([0-9]{4})([0-9]{4})$", "$1-$2-$3");
}
return src.replaceFirst("(^02|[0-9]{3})([0-9]{3,4})([0-9]{4})$", "$1-$2-$3");
}
public static void main(String[] args) {
System.out.println(FormatUtil.phone("01012341234"));
System.out.println(FormatUtil.phone("0212341234"));
System.out.println(FormatUtil.phone("03212341234"));
System.out.println(FormatUtil.phone("0621231234"));
System.out.println(FormatUtil.phone("0163451234"));
System.out.println(FormatUtil.phone("#012"));
System.out.println(FormatUtil.phone("15881588"));
System.out.println(FormatUtil.phone("050612341234"));
}
}
결과
010-1234-1234 02-1234-1234 032-1234-1234 062-123-1234 016-345-1234 #012 1588-1588 0506-1234-1234 |
정확한 스펙에 맞게하고 싶은분은 여기를 참조하셔서 직접 구현하셔도 됩니다.
링크 : 대한민국의 전화번호 체계
출처: https://goni9071.tistory.com/174 [고니의꿈]