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

Java 문자열 치환 완벽 가이드: replace(), replaceFirst(), replaceAll() 메서드 차이와 예제


1. replace() 메서드

String 클래스의 replace() 메서드는 두 개의 문자열(String) 값을 인자로 받습니다.

  • 문자열에서 교체하고자 하는 부분(부분 문자열)

  • 지정한 부분 문자열을 대체할 새로운 문자열

이 메서드를 활용하면 자바에서 문자열의 일부를 손쉽게 다른 내용으로 바꿀 수 있습니다.

예제 1: 파일 내용에서 특정 단어 교체하기

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReplaceExample {
   public static void main(String args[]) throws FileNotFoundException {
      String filePath = "D://input.txt";
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      String input;
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      String contents = sb.toString();
      System.out.println("Contents of the file: \n"+contents);
      System.out.println(" ");
      // 원하는 단어를 새 단어로 교체
      contents = contents.replace("Tutorialspoint", "TP");
      System.out.println("Contents of the file after replacing the desired word: \n"+contents);
   }
}

실행 결과

Contents of the file:
Hello how are you welcome to Tutorialspoint. At Tutorialspoint provide hundreds of technical tutorials for free.

Contents of the file after replacing the desired word:
Hello how are you welcome to TP. At TP provide hundreds of technical tutorials for free.

replace() 메서드에는 문자열 대신 char 타입 두 개(기존 문자, 새 문자 순서)를 인자로 받는 형태도 있습니다. 이 경우 문자열 전체에서 기존 문자가 발견되는 모든 위치가 새 문자로 교체됩니다.

예제 2: 특정 문자 교체하기

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReplaceExample {
   public static void main(String args[]) throws FileNotFoundException {
      String filePath = "D://input.txt";
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      String input;
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      String contents = sb.toString();
      System.out.println("Contents of the file: \n"+contents);
      System.out.println(" ");
      // 특정 문자를 새 문자로 교체
      contents = contents.replace('T', '#');
      System.out.println("Contents of the file after replacing the desired word: \n"+contents);
   }
}

실행 결과

Contents of the file:
Hello how are you welcome to Tutorialspoint. At Tutorialspoint provide hundreds of technical tutorials for free.

Contents of the file after replacing the desired word:
Hello how are you welcome to #utorialspoint. At #utorialspoint provide hundreds of technical tutorials for free.

2. replaceAll() 메서드

String 클래스의 replaceAll() 메서드는 정규 표현식과 대체할 패턴(문자열)을 인자로 받으며, 정규 표현식과 일치하는 모든 부분을 지정한 패턴/문자열로 교체합니다.

예제: 정규 표현식으로 단어 교체하기

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReplaceAllExample {
   public static void main(String args[]) throws FileNotFoundException {
      String filePath = "D://input.txt";
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      String input;
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      String contents = sb.toString();
      System.out.println("Contents of the file: \n"+contents);
      System.out.println();
      // \b는 단어 경계를 의미하므로 'Tutorialspoint'라는 독립된 단어만 교체됩니다.
      contents = contents.replaceAll("\\bTutorialspoint\\b", "TP");
      System.out.println("Contents of the file after replacing the desired word: \n"+contents);
   }
}

실행 결과

Contents of the file:
Hello how are you welcome to Tutorialspoint. At Tutorialspoint provide hundreds of technical tutorials for free.

Contents of the file after replacing the desired word:
Hello how are you welcome to TP. At TP provide hundreds of technical tutorials for free.

3. replaceFirst() 메서드

String 클래스의 replaceFirst() 메서드 역시 정규 표현식과 대체 문자열을 인자로 받는다는 점은 replaceAll()과 같지만, 가장 처음 일치하는 한 곳만 대체 문자열로 바꿉니다.

예제: 첫 번째 일치 항목만 교체하기

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReplaceExample {
   public static void main(String args[]) throws FileNotFoundException {
      String filePath = "D://input.txt";
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      String input;
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      String contents = sb.toString();
      System.out.println("Contents of the file: \n"+contents);
      System.out.println(" ");
      // 첫 번째로 일치하는 단어만 교체
      contents = contents.replaceFirst("Tutorialspoint", "TP");
      System.out.println("Contents of the file after replacing the desired word: \n"+contents);
   }
}

실행 결과

Contents of the file:
Hello how are you welcome to Tutorialspoint. At Tutorialspoint provide hundreds of technical tutorials for free.

Contents of the file after replacing the desired word:
Hello how are you welcome to TP. At Tutorialspoint provide hundreds of technical tutorials for free.

세 메서드 비교 요약

메서드매개변수교체 범위
replace()문자열 또는 char일치하는 모든 부분
replaceAll()정규 표현식 + 대체 문자열정규식과 일치하는 모든 부분
replaceFirst()정규 표현식 + 대체 문자열첫 번째 일치 항목만

참고: 세 메서드는 모두 대소문자를 구분합니다. 예를 들어 replace("java", "Kotlin")은 "Java"를 교체하지 못합니다. 대소문자 구분 없이 치환하려면 replaceAll()에서 정규 표현식 플래그 (?i)를 활용하는 방법을 고려할 수 있습니다.