CodeWars 일백 열 일곱 번째 문제
Updated:
Phone Directory
public static String phone(String strng, String num) {
if(!strng.contains("+" + num)) {
return "Error => Not found: " + num;
}
if(strng.replaceFirst("\\+" + num, "").contains("+" + num)) {
return "Error => Too many people: " + num;
}
Pattern findPattern = Pattern.compile("\n?.*\\+"+ num + ".*\n?");
Matcher findMatcher = findPattern.matcher(strng);
String findString = "";
while(findMatcher.find()) {
findString = findMatcher.group().replaceAll("\n", "").replaceAll("\\s*\\S*\\d+-\\d+-\\d+-\\d+\\S*", "");
}
String[] result = new String[] {"Phone => " + num, "Name => ", "Address => "};
result[1] += findString.replaceAll(".*<|>.*", "");
result[2] += findString.replaceAll("\\s*\\<.*\\>", "").replaceAll("^\\W*\\_*|[^\\w\\.]$", "").replaceAll("[\\s;,_]+", " ");
return String.join(", ", result);
}
- 정규식에 자신감이 생겨서 정규식에 너무 집중하다보니 원초적으로 로직으로 간단하게 풀 수 있는 것을 어렵게 푼듯 하다.
- 전화번호 앞에 “+” 붙는걸 까먹고 있어서 한시간을 해맸다….하 ㅅㅂ
- 아래 Best 코드랑 비교했을 때 앞단 해당 번호가 있는 줄을 뽑아 내는 것은 내 정규식 패턴이 좋은 것 같다.
- 그러나 아래 이름과 주소를 뽑아내는건… 저렇게 쉽게 뽑아 낼 수 있었는데 나는 너무 어렵게 한 것 같다.
public static String phone(String strng, String num) {
String found = null;
int count = 0;
for (String entry : strng.split("\n"))
if (entry.contains("+" + num)) {
found = entry;
count++;
}
// error cases
if (count == 0) return "Error => Not found: " + num;
if (count > 1) return "Error => Too many people: " + num;
// process found entry
String name = found.split("<|>")[1];
String address = found
.replace(name, "").replace(num, "") // only address left
.replaceAll("[^A-Za-z0-9\\. -]", " ") // filter all unnecessary chars
.trim().replaceAll(" +", " "); // reduce extra spaces
return "Phone => " + num + ", Name => " + name + ", Address => " + address;
}