Java - String.matches(REGEX)

준하·2024년 12월 14일
1
post-thumbnail

2019 카카오 개발자 겨울 인턴십 - 불량 사용자

내 정답 코드

import java.util.*;

class Solution {
    boolean[] visited;
    List<Integer>[] cases;
    Set<String> answerSet = new HashSet<>();
    
    void dfs(int idx) {
        if(idx == cases.length) {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < visited.length; i++) {
                if(visited[i]) sb.append(i);
            }
            answerSet.add(sb.toString());
            return;
        }
        
        List<Integer> possibles = cases[idx];
        
        for(int p : possibles) {
            if(visited[p]) continue;
            
            visited[p] = true;
            dfs(idx + 1);
            visited[p] = false;
        }
    }
    
    boolean isMatched(String a, String b) {
        if(a.length() != b.length()) return false;
        for(int i = 0; i < a.length(); i++) {
            if(a.charAt(i) == '*' || b.charAt(i) == '*') continue;
            if(a.charAt(i) != b.charAt(i)) return false;
        }
        return true;
    }
    
    public int solution(String[] user_id, String[] banned_id) {
        visited = new boolean[user_id.length];
        cases = new List[banned_id.length];
        
        for(int i = 0; i < banned_id.length; i++) {
            cases[i] = new ArrayList<>();
            for(int j = 0; j < user_id.length; j++) {
                if(isMatched(banned_id[i], user_id[j])) {
                    cases[i].add(j);
                }
            }
        }
        
        dfs(0);
        
        return answerSet.size();
    }
}

matches(String regex)

문제에서는 user_id 와 문자열의 일부가 '*'로 이루어진 banned_id가 매칭되는지를 파악해야한다.

boolean isMatched(String a, String b) {
        if(a.length() != b.length()) return false;
        for(int i = 0; i < a.length(); i++) {
            if(a.charAt(i) == '*' || b.charAt(i) == '*') continue;
            if(a.charAt(i) != b.charAt(i)) return false;
        }
        return true;
    }

나는 위와 같이 일일이 파악하였으나(ㅎㅎ;)
풀고나서 다른 사람의 풀이를 보다가 String 클래스에서 제공하는 matches 메서드를 알게되었다.

matches()는 문자열을 정규표현식과 매칭되는지 파악해주는 유용한 함수이다

String reg = banned_id.replace("*", "[\\w]") 
if(user_id.matches(reg)) {
	///매칭되는경우
}

banned_id에서 *를 전부 [\\w] 로 변경한 Regular Expression에 대해 matches() 메서드를 호출하면 쉽게 파악할 수 있다!

\w: 알파벳(a-z, A-Z), 숫자(0-9), 밑줄(_)을 포함합니다.
\d: 숫자(0-9)를 포함합니다.

profile
A Sound Code in a Sound Body💪

1개의 댓글

comment-user-thumbnail
2024년 12월 23일

잘 보고 갑니다 !!

답글 달기