String 에서 Bracket(괄호) 을(를) 다뤄보기.


프로그래밍으로 텍스트를 작업하다보면 괄호를 만나게 된다. 소괄호 혹은 중괄호 혹은 대괄호 등등 여기서 "(" , "[" , "{" 를 다루는 경우가 발생하는데, 해당 괄호 안의 내용을 추출해야 한다던지 혹은 해당 괄호 안의 내용을 제거해야한다는 경우가 생긴다.


이번에 그러한 경우에 어떻게 하면 구현을 할 수 있을지 알아보고자 한다.


우선 아래와 같은 텍스트의 내용이 있다.



괄호 여러 개가 텍스트에 존재하며, 중첩된 것도 있고 시작점에 있는 것과 끝점에 있는 것도 보인다. 여기서 주어진 텍스트에서 괄호를 제거하거나 혹은 괄호 안의 내용을 추출하고자 한다.


나는 정규식을 이용할 것이고, 정규식을 테스트할 수 있는 사이트는 아래의 사이트를 참고하자. 테스트할 텍스트를 입력하고 본인이 만든 정규식을 테스트 할 수 있는 유용한 사이트이다.



자바 API 의 정규식 관련 객체인 Pattern 과 Matcher 를 적절히 이용하면 위의 요구사항을 해결할 수 있다. 우선 패턴을 두 개 만든다.



위에꺼는 괄호 패턴, 아래는 일반적인 공백이다.


(1) 괄호와 함께 괄호의 내부 내용을 모두 지우는 함수

  • while() 을 통해 주어진 텍스트에 매칭되는 괄호 패턴을 파악

  • start() 와 end() 를 통해서 괄호 패턴의 시작점과 끝점을 획득

  • removeTextArea 영역을 substring() 로 획득

  • 이후에 replace 및 replace 된 텍스트를 가지고 다시 괄호패턴을 파악

  • 이와 같은 과정을 계속 반복


(2) 괄호 내부의 텍스트를 모두 추출하는 함수

  • (1) 과 동일한 로직

  • 약간 다른 부분은 추출된 괄호 텍스트를 ArrayList 에 삽입하는 형태

  • 왜 ArrayList 를 사용하였냐면 주어진 텍스트에 몇 개의 괄호가 존재할 지 모르기 때문


● 결과 내용 확인

  • 순서대로 

    • 주어진 텍스트 목록

    • 괄호를 제거한 텍스트 목록

    • 괄호 내용을 추출한 텍스트 목록



오늘 해본 내용은 여기까지고, 위의 내용을 구현한 소스는 아래에 있다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package blog;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexrTester {
    
    private static final Pattern PATTERN_BRACKET = Pattern.compile("\\([^\\(\\)]+\\)");
    private static final String VOID = "";
    
    public static void main(String[]args) {
        
        /**
         * (1) 괄호 내용 제거하기.
         * (2) 괄호 내용 추출하기
         */
        
        String text1 = "코딩 인터뷰 완전분석 (Cracking The Coding Interview), (2019년 2월 16일(doubler 또는 쌍기역))";
        
        String text2 = "컴퓨터 구조론(김종현 지음), 운영체제(최현섭, 오상엽, 박남일 지음), 고리오 영감 (오노레 드 발자크 지음)";
        
        String text3 = "(2019년 2월 15일) / (2019년 2월 16일) => 코딩은 언제나 즐겁다. 매번 어렵기도 하지만... 그래도 괜찮아";
        
        String text4 = "(고구마(사과(딸기(참외(수박))))) 이 모든 것들은 괄호 안에 있습니다.";
 
        
        System.out.println();
        System.out.println("** [주어진 텍스트 목록]");
        System.out.println("text1 :: " + text1);
        System.out.println("text2 :: " + text2);
        System.out.println("text3 :: " + text3);
        System.out.println("text4 :: " + text4);
        
        System.out.println("\nㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ\n");
        
        System.out.println("** [괄호를 제거한 텍스트 목록]");
        System.out.println("text1 :: " + deleteBracketTextByPattern(text1));
        System.out.println("text2 :: " + deleteBracketTextByPattern(text2));
        System.out.println("text3 :: " + deleteBracketTextByPattern(text3));
        System.out.println("text4 :: " + deleteBracketTextByPattern(text4));
        
        System.out.println("\nㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ\n");
        
        System.out.println("** [괄호 내용을 추출한 텍스트 목록]");
        System.out.println("text1 :: " + Arrays.toString(findBracketTextByPattern(text1).toArray()));
        System.out.println("text2 :: " + Arrays.toString(findBracketTextByPattern(text2).toArray()));
        System.out.println("text3 :: " + Arrays.toString(findBracketTextByPattern(text3).toArray()));
        System.out.println("text4 :: " + Arrays.toString(findBracketTextByPattern(text4).toArray()));
        
    }
    
    /**
     * 텍스트에 존재하는 괄호 모두 제거 모듈 <p>
     * @param text
     * @return
     */
    private static String deleteBracketTextByPattern(String text) {
        
        Matcher matcher = PATTERN_BRACKET.matcher(text);
        
        String pureText = text;
        String removeTextArea = new String();
        
        while(matcher.find()) {
            int startIndex = matcher.start();
            int endIndex = matcher.end();
            
            removeTextArea = pureText.substring(startIndex, endIndex);
            pureText = pureText.replace(removeTextArea, VOID);
            matcher = PATTERN_BRACKET.matcher(pureText);
        }
        
        return pureText;
    }
    
    /**
     * 텍스트에 존재하는 괄호 내용 모두 추출 <p>
     * @param text
     * @return
     */
    private static List<String> findBracketTextByPattern(String text){
        
        ArrayList<String> bracketTextList = new ArrayList<String>();
 
        Matcher matcher = PATTERN_BRACKET.matcher(text);
        
        String pureText = text;
        String findText = new String();
        
        while(matcher.find()) {
            int startIndex = matcher.start();
            int endIndex = matcher.end();
            
            findText = pureText.substring(startIndex, endIndex);
            pureText = pureText.replace(findText, VOID);
            matcher = PATTERN_BRACKET.matcher(pureText);
 
            /** 추출된 괄호 데이터를 삽입  **/
            bracketTextList.add(findText);
        }
        
        return bracketTextList;
    }
}
 
cs


Posted by doubler
,