Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java Matcher replaceAll() 메서드 완벽 가이드 – 실전 예제로 배우기

Matcher 클래스란 무엇인가?

java.util.regex.Matcher 클래스는 입력 문자열에 대해 다양한 패턴 매칭 작업을 수행하는 엔진 역할을 하는 클래스입니다. 이 클래스는 별도의 생성자가 없으며, java.util.regex.Pattern 클래스의 matcher() 메서드를 호출하여 객체를 생성하거나 얻을 수 있습니다.

Matcher 클래스의 replaceAll() 메서드는 문자열 값을 인자로 받아, 입력 문자열에서 패턴과 일치하는 모든 하위 시퀀스를 해당 문자열로 치환하고 그 결과를 반환합니다.

예제 1: 특수 문자 치환하기

다음 예제는 사용자로부터 입력받은 텍스트에서 특수 문자([# % & *])의 개수를 세고, 이를 모두 느낌표(!)로 치환하는 프로그램입니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      // 패턴 객체 생성
      Pattern pattern = Pattern.compile(regex);
      // Matcher 객체 생성
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      // 특수 문자 개수 출력
      System.out.println("The are "+count+" special characters [# % & *] in the given text");
      // 모든 특수 문자를 ! 로 치환
      String result = matcher.replaceAll("!");
      System.out.println("Replaced all special characters [# % & *] with !: \n"+result);
   }
}

실행 결과

Enter input text:
Hello# How # are# you *& welcome to T#utorials%point
The are 7 special characters [# % & *] in the given text
Replaced all special characters [# % & *] with !:
Hello! How ! are! you !! welcome to T!utorials!point

예제 2: 불필요한 공백 정리하기

정규식 \s+는 하나 이상의 연속된 공백 문자를 의미합니다. 아래 예제는 문장 내의 여러 개의 연속된 공백을 단일 공백으로 치환하여 텍스트를 깔끔하게 정리하는 방법을 보여줍니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String args[]) {
      // 사용자로부터 문자열 입력받기
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      // 하나 이상의 공백과 일치하는 정규식
      String regex = "\\s+";
      // 정규식 컴파일
      Pattern pattern = Pattern.compile(regex);
      // Matcher 객체 가져오기
      Matcher matcher = pattern.matcher(input);
      // 모든 공백 문자를 단일 공백으로 치환
      String result = matcher.replaceAll(" ");
      System.out.print("Text after removing unwanted spaces: \n"+result);
   }
}

실행 결과

Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces

정리

Matcher의 replaceAll() 메서드는 정규식 패턴과 일치하는 모든 부분을 지정한 문자열로 한 번에 교체할 수 있는 강력한 도구입니다. 특수 문자 제거, 공백 정리, 데이터 포맷 변환 등 텍스트 전처리 작업에서 널리 활용되므로, 위 예제들을 직접 실행해 보며 익혀두면 실무에서 큰 도움이 됩니다.