Tech
Swift 에서 휴대폰 번호 이쁘게 만들기
가루군#
2020. 5. 27. 21:52
01012341234
02123124
158812312
이런 숫자를 하이픈 넣어서 이쁘게 해주세요! 의 결과물
사실 별건없다 인터넷에서 이것저것 주워온 정규식 짬뽕물.
extension String {
func pretty() -> String {
let _str = self.replacingOccurrences(of: "-", with: "") // 하이픈 모두 빼준다
let arr = Array(_str)
if arr.count > 3 {
let prefix = String(format: "%@%@", String(arr[0]), String(arr[1]))
if prefix == "02" { // 서울지역은 02번호
if let regex = try? NSRegularExpression(pattern: "([0-9]{2})([0-9]{3,4})([0-9]{4})", options: .caseInsensitive) {
let modString = regex.stringByReplacingMatches(in: _str, options: [],
range: NSRange(_str.startIndex..., in: _str),
withTemplate: "$1-$2-$3")
return modString
}
} else if prefix == "15" || prefix == "16" || prefix == "18" { // 썩을 지능망...
if let regex = try? NSRegularExpression(pattern: "([0-9]{4})([0-9]{4})", options: .caseInsensitive) {
let modString = regex.stringByReplacingMatches(in: _str, options: [],
range: NSRange(_str.startIndex..., in: _str),
withTemplate: "$1-$2")
return modString
}
} else { // 나머지는 휴대폰번호 (010-xxxx-xxxx, 031-xxx-xxxx, 061-xxxx-xxxx 식이라 상관무)
if let regex = try? NSRegularExpression(pattern: "([0-9]{3})([0-9]{3,4})([0-9]{4})", options: .caseInsensitive) {
let modString = regex.stringByReplacingMatches(in: _str, options: [],
range: NSRange(_str.startIndex..., in: _str),
withTemplate: "$1-$2-$3")
return modString
}
}
}
return self
}
}
사용법은
"021231234".pretty()
끝.
오늘도 열심히 살자!
ㅠㅠ