Pattern과 Mather 클래스

✒️ 2025-05-29 17:38 내용 수정


Pattern 클래스

Java에서 사용하는 정규 표현식의 컴파일된 표현

// compile 함수의 매개변수로 정규표현식 전달
Pattern p = Pattern.compile(regex);

Pattern p1 = Pattern.compile("p");
// 숫자만 확인하는 정규표현식
Pattern p = Pattern.compile("\\d");
메서드 설명
static Pattern compile(String regex) 정규 표현식을 컴파일
static Pattern compile(String regex, int flags) 정규 표현식과 플래그를 컴파일
Matcher matcher(CharSequence input) 문자열과 패턴을 비교할 Matcher 객체 반환
static boolean matches(String regex, CharSequence input) 정규 표현식을 컴파일하고, 문자열과 비교한 Matcher 객체 반환
String pattern() 컴파일된 정규 표현식 반환

Matcher 클래스

해석한 정규 표현식과 문자열의 일치 여부를 확인하는 클래스

Pattern p1 = Pattern.compile("p");
Matcher m = p.matcher("pineapple");

System.out.println(m.matches()); // false

메서드

  1. matches() : 문자열 전체와 패턴의 일치 여부를 확인한다.
Pattern p = Pattern.compile("p");
Matcher m = p.matcher("pineapple");

System.out.println(m.matches()); // false
  1. lookingAt() : 문자열의 시작 부분이 패턴과 일치하는지 확인한다.
Pattern p = Pattern.compile(".");
Matcher m = p.matcher("pineapple");

System.out.println(m.lookingAt()); // true

Pattern p2 = Pattern.compile("i");
Matcher m2 = p2.matcher("pineapple");

System.out.println(m2.lookingAt()); // false
  1. find() : 문자열에서 패턴과 일치하는 문자를 확인한다.
    • 문자 내에 패턴을 하나라도 포함한다면 true
Pattern p = Pattern.compile("p");
Matcher m = p.matcher("pineapple");

System.out.println(m.find()); // true

Pattern p2 = Pattern.compile("i");
Matcher m2 = p2.matcher("pineapple");

System.out.println(m2.find()); // true
메서드 설명
matches() 문자열 전체가 패턴과 일치하는지 확인
lookingAt() 문자열의 시작 부분이 패턴과 일치하는지 확인
find() 문자열에서 패턴과 일치하는 문자를 확인
group() 이전 매칭에서 전체 일치한 부분을 반환
group(int group) 지정한 그룹 번호에 해당하는 캡처(())된 부분을 반환
groupCount() 패턴과 매칭된 그룹 개수 반환
start() 이전 매칭의 시작 인덱스를 반환
end() 이전 매칭의 끝 인덱스를 반환
replaceAll(String replacement) 입력 시퀀스에서 패턴과 일치하는 모든 부분을 지정한 문자열로 교체
replaceFirst(String replacement) 입력 시퀀스에서 패턴과 일치하는 첫 번째 부분을 지정한 문자열로 교체
reset() Matcher의 상태를 초기화하여 새로운 매칭 작업을 시작할 수 있도록 함
import java.util.regex.*;  
  
// 문자 뒤에 느낌표가 오는 부분 문자열 반환
public class RegexTest {  
    public static void main(String[] args) {  
        String input = "Hello! World! Java is Awesome!";
        Pattern p = Pattern.compile("\\w+!");  
        Matcher m = p.matcher(input);  
        
        while (m.find()) {  
            System.out.println(m.group());  
        }  
    }  
}
Hello!
World!
Awesome!