English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
java.util.regex.Matcher 클래스는 다양한 매칭 작업을 수행하는 엔진을 나타냅니다. 이 클래스에는 생성자가 없으며, java.util.regex.Pattern 클래스의 matches() 메서드를 사용하여 생성할 수 있습니다/이 클래스의 객체를 얻습니다.
이 (Matcher) 클래스의 appendReplacement() 메서드는 StringBuffer 객체와 String(대체 문자열)을 매개변수로 받아 입력 데이터를 StringBuffer 객체에 추가하고, 대체 문자열로 매칭된 내용을 대체합니다.
내부에서 이 메서드는 입력 문자열에서 각 문자를 읽고 StringBuffer에 추가하고, 매칭이 발생할 때마다 문자열을 대신 추가하지 않고 매칭된 내용 부분을 StringBuffer에 추가하고, 매칭된 서브 문자열의 다음 위치에서 계속 진행합니다.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class appendReplacementExample { public static void main(String[] args) { String str = "<p>This <b>is</b> an <b>example</b>HTML <b>script</b>.</p>"; //Regular expression to match contents of the bold tags String regex = "<b>(\\S+)</b>"; System.out.println("Input string: \n"+str); //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(str); //Creating an empty string buffer StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, "BoldData"); } matcher.appendTail(sb);} System.out.println("StringBuffer의 내용:\n");+ sb.toString()); } }
출력 결과
입력 문자열: <p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p> StringBuffer의 내용: This BoldData an BoldData HTML BoldData. <p>This BoldData an BoldData HTML BoldData.</p>
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class appendReplacementExample { 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; StringBuffer buffer = new StringBuffer(); System.out.println("Removing the special character from the given string"); while(matcher.find()) { count++; matcher.appendReplacement(buffer, ""); } matcher.appendTail(buffer); //Retrieving Pattern used System.out.println("The are special characters occurred "+count+" times in the given text"); System.out.println("Text after removing all of them \n"+buffer.toString()); } }
출력 결과
Enter input text: Hello# how$ are& yo|u welco<me to> Tut-oria@ls@po-in#t. Removing the special character form the given string The are special characters occurred 11 times in the given text Text after removing all of them Hello how are you welcome to w3codebox.