คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern
เมธอด appendReplacement() ของคลาส (Matcher) นี้รับ StringBuffer object และ String (replacement string) เป็นพารามิเตอร์ และนำข้อมูลอินพุตไปผนวกที่ StringBuffer object โดยแทนที่เนื้อหาที่จับคู่ได้ด้วย replacement string
ภายใน เมธอดนี้อ่านตัวอักษรแต่ละตัวจากสตริงอินพุตและผนวก String buffer ทุกครั้งที่มีการจับคู่ จะผนวก replacement string แทนส่วนของสตริงที่จับคู่ได้ และดำเนินการต่อจากตำแหน่งถัดไปของ substring ที่จับคู่ได้
ตัวอย่างที่ 1: แทนที่เนื้อหาใน <b> tags
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);
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// จับคู่ pattern ที่คอมไพล์แล้วใน String
Matcher matcher = pattern.matcher(str);
// สร้าง StringBuffer ว่าง
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "BoldData");
}
matcher.appendTail(sb);
System.out.println("Contents of the StringBuffer: \n" + sb.toString());
}
}
Output
Input string: <p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p> Contents of the StringBuffer: This BoldData an BoldData HTML BoldData. <p>This BoldData an BoldData HTML BoldData.</p>
ตัวอย่างที่ 2: ลบอักขระพิเศษด้วย appendReplacement()
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 = "[#$&+=@|<>-]";
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
StringBuffer buffer = new StringBuffer();
System.out.println("Removing the special character form the given string");
while (matcher.find()) {
count++;
matcher.appendReplacement(buffer, "");
}
matcher.appendTail(buffer);
// ดึง Pattern ที่ใช้
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());
}
}
Output
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 Tutorialspoint.