IT/JAVA

Pattern, Matcher Class

iamhyeon 2025. 2. 25. 16:57

Java에는 정규식을 활용해 문자열을 검증, 탐색을 돕는 Pattern, Matcher 클래스가 있다

Java API  java.util.regex 패키지에 포함되어 있다.

 

 

Pattern 클래스  (java.util.regex.Pattern)

- 정규 표현식을 정의하는 클래스

- 정규 표현식을 컴파일하여 Pattern 객체를 생성한다

 

📝 matches() 메서드  :  검증 후 대상문자열이 정규표현식과 일치하면 true, 그렇지 않다면 false값을 리턴

import java.util.regex.Pattern;

public class RegexExample {
	public static void main(String[] args)  {
    
            String pattern = "^[0-9]*$"; //숫자만
            String val = "123456789"; //대상문자열
        
            boolean regex = Pattern.matches(pattern, val);
            System.out.println(regex);
    }
}

 

 

주요 메서드

compile(String regex) 주어진 정규표현식을 컴파일하여 Pattern 객체를 반환한다
matcher(CharSequence input) 주어진 입력 시퀀스에 대해 이 패턴을 매칭하는 Matcher 객체를 생성한다
pattern() 컴파일된 정규표현식을 String 형태로 반환한다
split(CharSequence input) 문자열을 주어진 인자값 CharSequence 패턴에 따라 분리한다

 

플래그 값 사용 (상수)

Pattern.CANON_EQ None표준화된 매칭 모드를 활성화한다
Pattern.CASE_INSENSITIVE 대소문자를 구분하지 않는다
Pattern.COMMENTS  공백과 #으로 시작하는 주석이 무시된다 (라인의 끝까지)
Pattern.MULTILINE 수식 ‘^’ 는 라인의 시작과, ‘$’ 는 라인의 끝과 match 된다
Pattern.DOTALL 수식 ‘.’과 모든 문자와 match 되고 ‘\n’ 도 match 에 포함된다
Pattern.UNICODE_CASE 유니코드를 기준으로 대소문자 구분 없이 match 시킨다
Pattert.UNIX_LINES 수식 ‘.’ 과 ‘^’ 및 ‘$’의 match시에 한 라인의 끝을 의미하는 ‘\n’만 인식된다

 

 

Matcher 클래스

- Pattern 객체와 입력 시퀀스 간의 매칭 작업을 수행하는 클래스이다

- Pattern 객체를 사용하여 생성된다

- 대상 문자열의 패턴을 해석하고 주어진 패턴과 일치하는지 판별할 때 주로 사용된다

- 입력값으로 CharSequence라는 새로운 인터페이스가 사용되는데 이를 통해 다양한 형태의 입력 데이터로부터 문자 단위의 매칭 기능을 지원받을 수 있다.

 

📝 Matcher객체는 Pattern객체의 matcher() 메서드를 호출하여 받아올 수 있다

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

public class RegexExample {
	public static void main(String[] args)  {
            Pattern pattern = Pattern.compile("^[a-zA-Z]*$"); //영문자만
            String val = "abcdef"; //대상문자열
	
            Matcher matcher = pattern.matcher(val);
            System.out.println(matcher.find());
	}
}

 

주요 메서드

matches() 입력 시퀀스 전체가 패턴과 일치하는지 확인한다 [ true | false ]
find() 입력 시퀀스에서 패턴과 일치하는 다음 부분을 찾는다
group() 마지막으로 매칭된 부분을 반환한다
group(int group) 특정 그룹에 매칭된 부분을 반환한다

 


📝 유효성 검사

import java.util.regex.Pattern;

public class RegexExample {
	public static void main(String[] args)  {
          String name = "홍길동";
          String tel = "010-1234-5678";
          String email = "test@naver.com";
         
          //유효성 검사
          boolean name_check = Pattern.matches("^[가-힣]*$", name);
          boolean tel_check = Pattern.matches("^01(?:0|1|[6-9])-(?:\\d{3}|\\d{4})-\\d{4}$", tel);
          boolean email_check = Pattern.matches("\\w+@\\w+\\.\\w+(\\.\\w+)?", email);

          //출력
          System.out.println("이름 : " + name_check);
          System.out.println("전화번호 : " + tel_check);
          System.out.println("이메일 : " + email_check);
    }
}

 


📝 JadenCase 문자열 만들기 (프로그래머스_12951)

- 모든 단어의 첫 문자가 대문자이고, 그 외의 알파벳은 소문자인 문자열 반환

- 첫 문자가 알파벳이 아닐 때에는 이어지는 알파벳은 소문자로 쓰면 된다.
- 문자열 s가 주어졌을 때, s를 JadenCase로 바꾼 문자열을 리턴하는 함수, solution을 완성.

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

public class JadenCase문자열만들기_3 {

    public String solution(String s) {
        // 단어의 첫 글자와 나머지 글자를 그룹으로 나누는 정규 표현식을 컴파일한다.
        // \\b: 단어 경계를 나타낸다. 단어의 시작이나 끝을 의미
        // ([\\w]): 단어의 첫 글자를 캡처하는 그룹
        // ([\\w]*): 단어의 나머지 글자를 캡처하는 그룹
        // matcher(s): 입력 문자열 s에 대해 매칭 작업을 수행하는 Matcher 객체를 생성한다.
        Matcher m = Pattern.compile("\\b([\\w])([\\w]*)").matcher(s);
        
        StringBuffer sb = new StringBuffer();

        // 입력 문자열에서 패턴과 일치하는 부분을 찾는다
        while (m.find()) {
            // 매칭된 부분을 대체하여 StringBuffer에 추가한다. 
            m.appendReplacement(sb, m.group(1).toUpperCase() + m.group(2).toLowerCase());
        }
        // 마지막으로 매칭되지 않은 부분을 StringBuffer에 추가한다.
        m.appendTail(sb);

        return sb.toString();
    }

    public static void main(String[] args) {
        JadenCase문자열만들기_3 s = new JadenCase문자열만들기_3();
        System.out.println(s.solution("3people unFollowed me"));
        System.out.println(s.solution("for the last week"));
    }
    
}

 

 

 

 

 


refer to 

https://girawhale.tistory.com/77

https://yunamom.tistory.com/224

 

 

'IT > JAVA' 카테고리의 다른 글

코드 실행시간 비교  (0) 2025.03.26
HashSet  (0) 2025.03.20
StringBuilder  (0) 2025.01.19
IntStream  (0) 2025.01.04
Stream  (0) 2025.01.03