java.util.regex.Matcher 클래스는 다양한 일치 작업을 수행하는 엔진을 나타냅니다. 이 클래스에 대한 생성자가 없습니다. java.util.regex.Pattern 클래스의 matching() 메소드를 사용하여 이 클래스의 객체를 생성/얻을 수 있습니다.
이 (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 = "[#%&*]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
int count =0;
while(matcher.find()) {
count++;
}
//Retrieving Pattern used
System.out.println("The are "+count+" special characters [# % & *] in the given text");
//Replacing all special characters [# % & *] with ! 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
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match spaces (one or more)
String regex = "\\s+";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
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