English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이java.util.regex.Matcher의이 클래스는 매칭 엔진을 대표합니다. 이 클래스는 생성자가 없으며 사용할 수 있습니다.matches()
java.util.regex.Pattern 클래스의 메서드로 생성됩니다/이 클래스의 객체를 얻습니다.
에서replaceAll()
이 클래스의 메서드는 문자열 값을 받아 모든 일치하는 서브 시퀀스를 주어진 문자열 값으로 대체하고 결과를 반환합니다.
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("입력 텍스트를 입력하세요: "); 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는 "+count+"특수 문자 [# % & *]를 주어진 텍스트에서 제거합니다"); //모든 특수 문자 [# % &를 대체하고 있습니다 *]와 ! String result = matcher.replaceAll("!"); System.out.println("모든 특수 문자 [# % &를 대체했습니다 *]와 !: "+result); } }
출력 결과
입력 텍스트를 입력하세요: 안녕# 어떻게 되세요#? *& 환영합니다! T#utorials%point로 오셨습니다 The는 7 특수 문자 [# % & *]를 주어진 텍스트에서 제거했습니다 모든 특수 문자 [# % &를 대체했습니다 *]와 !: 안녕하세요! 어떻게 되세요? 환영합니다! Tutorials point로 오셨습니다!
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 = 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