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.

更新日期:2019 年 11 月 20 日

498 次瀏覽

開啟你的 職業生涯

透過完成該課程獲得認證

立即開始
廣告