String 클래스의 split() 메서드는 현재 문자열을 주어진 정규 표현식과 일치하는 패턴을 기준으로 분리합니다. 이 메서드가 반환하는 배열에는 지정한 정규 표현식에 일치하는 구분자 또는 문자열의 끝을 경계로 잘린 각 부분 문자열이 담기게 됩니다.
또한 replaceAll() 메서드는 정규 표현식과 대체 문자열 두 개의 인자를 받아, 일치하는 모든 값을 지정한 문자열로 교체합니다.
구현 절차
파일의 내용 중 특정 단어를 제외한 모든 문자를 '#'으로 바꾸려면 다음 순서대로 진행합니다.
- 파일의 내용을 String으로 읽어옵니다.
- 비어 있는 StringBuffer 객체를 생성합니다.
- split() 메서드를 사용해 읽어온 문자열을 String 배열로 분리합니다.
- 생성된 배열을 순회하며 각 요소를 검사합니다.
- 요소가 보존하려는 단어와 일치하면 그대로 StringBuffer에 추가합니다.
- 나머지 단어들은 문자를 '#'으로 교체한 뒤 StringBuffer에 추가합니다.
- 마지막으로 StringBuffer를 String으로 변환하여 결과를 얻습니다.
예제
다음과 같은 내용을 담은 sample.txt 파일이 있다고 가정해 보겠습니다.
Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free.
아래 프로그램은 파일의 내용을 문자열로 읽어온 뒤, 지정된 단어를 제외한 나머지 모든 문자를 '#'으로 대체합니다.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ReplaceExcept {
public static String fileToString() 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);
}
return sb.toString();
}
public static void main(String args[]) throws FileNotFoundException {
String contents = fileToString();
System.out.println("Contents of the file: \n"+contents);
//Splitting the words
String strArray[] = contents.split(" ");
System.out.println(Arrays.toString(strArray));
StringBuffer buffer = new StringBuffer();
String word = "Tutorialspoint";
for(int i = 0; i < strArray.length; i++) {
if(strArray[i].equals(word)) {
buffer.append(strArray[i]+" ");
} else {
buffer.append(strArray[i].replaceAll(".", "#"));
}
}
String result = buffer.toString();
System.out.println(result);
}
}실행 결과
Contents of the file: Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free. [Hello, how, are, you, welcome, to, Tutorialspoint, we, provide, hundreds, of, technical, tutorials, for, free.] #######################Tutorialspoint ############################################
실행 결과에서 볼 수 있듯이, 'Tutorialspoint'라는 단어만 원본 그대로 유지되고 파일 내의 다른 모든 문자는 '#'으로 대체된 것을 확인할 수 있습니다. 이 방식은 로그 마스킹이나 민감 정보 가림 처리 등에도 유용하게 활용할 수 있습니다.