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.zaixian;
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-