Matcher 的 `appendReplacement()` 方法及其示例的 Java 版
java.util.regex.Matcher 类代表执行各种匹配操作的引擎。此类没有构造函数,你可以使用 java.util.regex.Pattern 类的 matches() 方法来创建/获取此类的对象。
此 (Matcher) 类的 appendReplacement() 方法接受一个 StringBuffer 对象和一个字符串(替换字符串)作为参数,并且将输入数据附加到 StringBuffer 对象,同时用替换字符串替换匹配的内容。
在内部,此方法从输入字符串中读取每个字符,并追加字符串缓冲区,每当出现匹配时,它会将替换字符串(而不是字符串的匹配内容部分)附加到缓冲区,然后从匹配子字符串的下一个位置继续。
示例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 Tutorialspoint.
广告