java.util.regex.Matcher.appendReplacement()



說明

java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) 方法實施了一個非終止符追加並替換步驟。

宣告

以下是 java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) 方法的宣告。

public Matcher appendReplacement(StringBuffer sb, String replacement)

引數

  • sb − 目標字串緩衝區。

  • replacement − 替換字串。

返回值

此匹配器。

異常

  • IllegalStateException − 如果尚未嘗試匹配,或者如果之前的匹配操作失敗。

  • IllegalArgumentException − 如果替換字串引用模式中不存在的命名捕獲組。

  • IndexOutOfBoundsException − 如果替換字串引用模式中不存在的捕獲組。

示例

以下示例展示了 java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) 方法的用法。

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "a*b";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      StringBuffer buffer = new StringBuffer();
      
      while(matcher.find()) {
         matcher.appendReplacement(buffer, REPLACE);
      }
      matcher.appendTail(buffer);
      System.out.println(buffer.toString());
   }
}

讓我們編譯並執行以上程式,這將產生以下結果 −

-foo-foo-foo-
javaregex_matcher.htm
廣告
© . All rights reserved.