Java中具有示例的Matcher appendReplacement()方法
java.util.regex.Matcher类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用类java.util.regex.Pattern的matchs()方法创建/获取此类的对象。
此(Matcher)类的appendReplacement()方法接受StringBuffer对象和String(替换字符串)作为参数,并将输入数据附加到StringBuffer对象,用替换字符串替换匹配的内容。
在内部,此方法从输入字符串中读取每个字符并追加String缓冲区,每当发生匹配时,它将替换字符串而不是字符串的匹配内容部分追加到缓冲区,然后从匹配子字符串的下一个位置继续。
例1
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("Contents of the StringBuffer: \n"+ sb.toString() ); } }
输出结果
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
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 form 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 Nhooo.