Notice
Recent Posts
Recent Comments
Link
투케이2K
233. (python/파이썬) [유틸 함수] getCallNumFormat 휴대폰 번호 및 지역 전화 번호 형식 문자열 포맷 함수 - compile , match 사용 본문
Python
233. (python/파이썬) [유틸 함수] getCallNumFormat 휴대폰 번호 및 지역 전화 번호 형식 문자열 포맷 함수 - compile , match 사용
투케이2K 2026. 4. 8. 19:39728x90
반응형
[개발 환경 설정]
개발 툴 : Aws / Lambda / Runtime Python 3.13
개발 언어 : python

[소스 코드]
// --------------------------------------------------------------------------------------
[개발 및 테스트 환경]
// --------------------------------------------------------------------------------------
- 언어 : Python
- 개발 툴 : Aws / Lambda / Runtime Python 3.13
- 개발 기술 : 유틸 함수 / getCallNumFormat
- 사전) 👉 re.compile 간략 설명 :
>> re.compile() 은 정규식을 미리 컴파일해서 객체로 만들어두는 함수입니다.
>> re.compile() 을 사용하기 위한 import 선언
import re
pattern = re.compile(r'\d+')
- 사전) 👉 match() 간략 설명 :
>> match() 는 문자열의 "처음부터" 정규식이 일치하는지 검사합니다. (항상 문자열의 시작(^)부터 검사)
>> compile + match 기본 사용법
import re
pattern = re.compile(r'\d+')
result = pattern.match("123abc")
if result:
print("매치됨:", result.group())
else:
print("매치 안 됨"
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
[소스 코드]
// --------------------------------------------------------------------------------------
# ========================================================================
# 🔵 [유틸 함수] : getCallNumFormat 휴대폰 번호 및 지역 전화 번호 형식 문자열 포맷 함수
# ========================================================================
# [참고] : API Gateway 와 연동 되어 Post 방식으로 Lambda 함수 호출 및 응답 값 반환 수행
# ========================================================================
import json
import os
import re
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# ========================================================================
# 🔵 [유틸 함수 정의]
# ========================================================================
def get_call_num_format(call_num: str) -> str:
"""
✔️ 전화번호 포맷 변환
return ex : 010-1234-5678
return ex : 02-1234-5678
return ex : 054-123-4567
"""
return_data = "" # 리턴 반환 변수
try:
if call_num is not None and call_num != "": # str null 체크 수행
# 휴대폰, 지역번호 모두 허용하는 정규식
pattern = re.compile(r'^(\d{2}|\d{3})-(\d{3}|\d{4})-\d{4}$')
# 이미 포맷이 맞는 경우 그대로 리턴
if pattern.match(call_num):
return_data = call_num
else:
# 특수문자 제거
replace_call_num = call_num
replace_call_num = re.sub(r'[!@#$%^&*().,?:;/_{}+=-]', '', replace_call_num)
replace_call_num = re.sub(r'\s+', '', replace_call_num) # 공백 제거
# 모두 숫자인지 체크
if replace_call_num.isdigit():
# ✅ 11자리 (01012345678)
if len(replace_call_num) == 11:
return_data = re.sub(
r'(\d{3})(\d{4})(\d{4})',
r'\1-\2-\3',
replace_call_num
)
# ✅ 10자리 (0212345678, 0541234567)
elif len(replace_call_num) == 10:
# 서울 제외 지역번호 (031~064)
sub_pattern = re.compile(r'^(0[3-6][1-4])(\d{3})\d{4}$')
if sub_pattern.match(replace_call_num):
return_data = re.sub(
r'(\d{3})(\d{3})(\d{4})',
r'\1-\2-\3',
replace_call_num
)
else:
# 서울 (02)
return_data = re.sub(
r'(\d{2})(\d{4})(\d{4})',
r'\1-\2-\3',
replace_call_num
)
else:
logger.error("[get_call_num_format] replace_call_num length match error")
else:
logger.error("[get_call_num_format] replace_call_num is not number")
except Exception as e:
logger.exception("[get_call_num_format] Exception")
logger.warning(f"[get_call_num_format] Length = {len(return_data)} / {return_data}")
return return_data
# ========================================================================
# 🔵 [파이썬 코드 수행 시 동작 되는 메인 함수]
# ========================================================================
def lambda_handler(event, context): # Lambda 호출 시 동작 되는 메인 함수
# [event , context 정보 디버깅 로그 출력]
print(f"DLOG = event : {event} / context {context}")
# [Return 반환 Json 변수 선언]
response = {
"statusCode" : 0,
"headers" : {},
"body" : ""
}
# ✅ [유틸 함수 호출 수행]
result_1 = get_call_num_format('01012345678')
result_2 = get_call_num_format('0212345678')
result_3 = get_call_num_format('0541234567')
# [리턴 변수 삽입]
response["statusCode"] = 200
response["headers"] = {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*', # CORS 허용 (필요 시)
}
response["body"] = json.dumps({
"result_1": result_1,
"result_2": result_2,
"result_3": result_3
})
# [리턴 반환 수행]
return response
# ========================================================================
"""
{
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": "{\"result_1\": \"010-1234-5678\", \"result_2\": \"02-1234-5678\", \"result_3\": \"054-123-4567\"}"
}
"""
# ========================================================================
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
[참고 사이트]
// --------------------------------------------------------------------------------------
▶️ [Mac Os] : [정규식] : 정규식 (regular expression) 사용해 한글 출력 수행 - 숫자, 영어, 특수 문자 제거
https://kkh0977.tistory.com/6169
https://blog.naver.com/kkh0977/223448888173?trackingCode=blog_bloghome_searchlist
▶️ [Mac Os] : [정규식] : 정규식 (regular expression) 사용해 영문자 출력 수행 - 숫자, 한글, 특수 문자 제거
https://kkh0977.tistory.com/6167
https://blog.naver.com/kkh0977/223448880222?trackingCode=blog_bloghome_searchlist
▶️ [Mac Os] : [정규식] : 정규식 (regular expression) 사용해 숫자 출력 수행 - 영어, 한글, 특수 문자 제거
https://kkh0977.tistory.com/6168
https://blog.naver.com/kkh0977/223448884510?trackingCode=blog_bloghome_searchlist
// --------------------------------------------------------------------------------------
728x90
반응형
'Python' 카테고리의 다른 글
Comments
