자바 Pattern 클래스

2019. 4. 1. 23:17알고리즘문제/Hackerrank

Pattern 클래스가 뭘까 정말 어렵다.

정규표현을 확인할 때 사용되는 건 알겠는데 어렵다.

 

정확히 어떤 클래스인지 아시는 분 댓글 부탁드려요 ㅜㅜ!!!!

 

정의

java.lang.Object

   - java.util.regex.Pattern

 

일단 Java Doc을 참고하면

" A compiled representation of a regular expression "

A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.

 

이렇게 Pattern이 정의되어 있다.

 

 

오로지 정규표현식을 compile 하기 위한 클래스인가 ??? !!

정의처럼 Pattern 클래스는 compile 메소드를 가장 많이 사용한다.

 

Method

- compile : 주어진 flags 조건대로 정규표현식(regex)를 컴파일한 후 Pattern클래스를 반환한다. 

Pattern p = Pattern.compile(regex, flags);

* 여기서 컴파일의 의미는 ? 잘 모르겠다.

* flags 의 종류로는  CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL and COMMENTS 가 있다.

 

- matcher : 패턴과 함께 input값을 매치하는 Matcher객체(정규표현엔진)를 만들어 반환한다. 

Matcher m = p.matcher(charSequence input);

 

- matches : 주어진 입력 문자에서 특별한 패턴을 빠르게 체크한다.

Pattern.matches(String regex, CharSequence input)

Compiles the given regular expression and attempts to match the given input against it.

 

* Matcher객체의 matches 메소드도 따로 있다.

ex) boolean b = m.matches();

주어진 패턴과 input값이 매치하는지 확인 후 결과 값을 논리형으로 반환한다.

 

 

문제

반복된 단어를 하나로 만들어 문장을 완성시켜라.

ex) input :  1

                   Hello heLLo heLlo Im iM dadee !

      output : Hello Im dadee !

 

위의 정수 1은 입력 스트링의 갯수를 의미한다. 정수가 3으로 주어진다면 입력 스트링과 출력 스트링은 3개가 될 것 !

 

역시나 Discussion에 천재적인 친구가 있었다. 

그의 풀이 !

 

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DuplicateWords {

    public static void main(String[] args) {

        String regex = "\\b(\\w+)(?:\\W+\\1\\b)+";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        Scanner in = new Scanner(System.in);
        int numSentences = Integer.parseInt(in.nextLine());
        
        while (numSentences-- > 0) {
            String input = in.nextLine();
            
            Matcher m = p.matcher(input);
            
            // Check for subsequences of input that match the compiled pattern
            while (m.find()) {
                input = input.replaceAll(m.group(), m.group(1));
            }
            
            // Prints the modified sentence.
            System.out.println(input);
        }
        
        in.close();
    }
}

 

풀이

* Regex  : "\b(\w+)(?:\W+\1\b)+"

\b : 단어 경계

\w : [a-zA-Z_0-9]  알파벳과 숫자, 그리고 _(언더바)를 찾음

\W : [^\w] 알파벳과 숫자, 그리고 _(언더바)가 아닌 것을 찾음

\1 : 부모 중 첫번째 그룹과 매치되는 것이 와라 !

+ : 앞 문자가 1개 혹은 그 이상임

? : 앞 문자가 없거나 하나 있음

 

*Groups

input = input.replaceAll(m.group(), m.group(1));

전체 그룹들을 기준 그룹으로 바꿔랑.

 

*m.find()

Attempts to find the next subsequence of the input sequence that matches the pattern.

 

 

 

참조

- flags 종류 설명

http://egloos.zum.com/ultteky/v/3945804

 

[정규식] Methods of the Pattern Class

스크랩 : http://neokido.tistory.com 지금까지 우리는 test harness를 이용하여 패턴 객체를 생성하고 그들의 기본 폼을 이용하였다. 이번 섹션에서는 좀더 향상된 기술로 플래그와 함깨 패턴을 생성하거나 포함된 플래그 표현들을 이용할 것이다. 우리가 아직 논의하지 않은 몇가지 유용한 추가적인 내용들에 대해서 논의할 것이다.

C

 

egloos.zum.com

 

- 그가 참고했다던 링크

http://tutorials.jenkov.com/java-regex/matcher.html

 

Java Regex - Matcher

This tutorial explains the Java Regex Matcher class which can match a pattern (regular expression) against one or more strings.

tutorials.jenkov.com

 

- 정규식으로 특정문자 제거하기

https://cityattack.tistory.com/64

 

[javascript&jQuery] 정규식으로 특정문자 제거

안녕하세요~ 블로그지기 인간대표 입니다. 자바스크립트에서 특정문자 또는 특수문자를 제거할때, -가 여러번 있는 문자열(주민번호,전화번호)을 단순히 replace('-','')로 하면, 처음 -기호만 삭제되고 나머지는..

cityattack.tistory.com