[Regex] Pattern and Matcher in Java

2022. 1. 21. 23:29개발공부/Java

728x90

Regex: Pattern and Matcher in Java


/*
 Predefined character classes
    .    Any character (may or may not match line terminators)
    \d    A digit: [0-9]
    \D    A non-digit: [^0-9]
    \s    A whitespace character: [ \t\n\x0B\f\r]
    \S    A non-whitespace character: [^\s]
    \w    A word character: [a-zA-Z_0-9]
    \W    A non-word character: [^\w]

Greedy quantifiers
    X?    X, once or not at all
    X*    X, zero or more times
    X+    X, one or more times
    X{n}    X, exactly n times
    X{n,}    X, at least n times
    X{n,m}    X, at least n but not more than m times
 */

private static final String completePattern2 = "COMPLETE: (\\w+)";

    public static void matcherPrac() {
        Pattern p = Pattern.compile(completePattern2);
        System.out.println(completePattern2);
        /* COMPLETE: (\w+)*/
        Matcher m = p.matcher("COMPLETE: k");
        /* true */
        System.out.println(m.find());
    }

괄호 ()를 하는 이유는 matcher group(int i) 메서드를 사용할 때 나눠서(split) 받아줄 수 있기 때문입니다. 예시 코드에서 COMPLETE: 가 group(0), 그 뒤의 정규식이 group(1)이 됩니다.


참고자료: