필요한 정규식을 컴파일하고 입력 문자열을 matcher() 메서드에 매개 변수로 전달하여 matcher 개체를 검색한 후
Matcher 클래스의 replaceAll() 메서드를 사용하여 입력 문자열의 일치하는 모든 부분을 다른 문자열로 바꿀 수 있습니다.
이 메서드는 문자열(교체 문자열)을 받아들이고 입력 문자열의 모든 일치 항목을 해당 문자열로 바꾸고 결과를 반환합니다.
예시 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\t+";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("No.of matches: "+count);
String result = matcher.replaceAll(" ");
System.out.println("Result: "+result);
}
} 출력
Enter input text: sample text with tab spaces No.of matches: 4 Result: sample text with tab spaces
같은 방법으로 Matcher 클래스의 replaceFirst() 메서드를 사용하여 첫 번째 일치 항목을 바꿀 수 있습니다.
예시 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\d";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("No.of matches: "+count);
String result = matcher.replaceFirst("#");
System.out.println("Result: "+result);
}
} 출력
Enter input text: test data 1 2 3 No.of matches: 3 Result: test data # 2 3