當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Matcher appendReplacement()用法及代碼示例


該方法用於實現 append-and-replace 步驟。首先,它用給定的輸入序列替換已編譯的字符或單詞,然後將給定的替換字符串附加到字符串緩衝區。

用法

public Matcher appendReplacement(StringBuffer strbuff, String replcmnt)

參數

strbuff- 目標字符串緩衝區

replcmnt- 替換字符串

返回

這個匹配器

拋出

IllegalStateException - 如果還沒有嘗試過匹配,或者之前的匹配操作失敗

IllegalArgumentException - 如果替換字符串引用模式中不存在的 named-capturing 組

IndexOutOfBoundsException - 如果替換字符串引用模式中不存在的捕獲組

例子1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherAppendReplacementExample1 {
	public static void main(String[] args) {
	//pattern/expression to be matched
	Pattern p = Pattern.compile("dog",Pattern.CASE_INSENSITIVE);
	//Regular expression
	Matcher m = p.matcher("'Let the dog come out of the bag'.To disclose a secret(Dog)");
	 // Creating the target string buffer
	StringBuffer sb = new StringBuffer();
	while (m.find()) {
m.appendReplacement(sb, "cat");//calling method System.out.println(sb.toString());
            }
       }
}

輸出:

'Let the cat
'Let the cat come out of the bag'.To disclose a secret(cat

例子2

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

public class MatcherAppendReplacementExample2 {

	public static void main(String[] args) {
	//pattern/expression to be matched
	Pattern p = Pattern.compile("dog",Pattern.CASE_INSENSITIVE);
	//Regular expression
	Matcher m = p.matcher("'Let the dog come out of the bag'.To disclose a secret(Dog)**");
	// Creating the target string buffer
	StringBuffer sb = new StringBuffer();
	while (m.find()) {
m.appendReplacement(sb, "cat");//calling method System.out.println(sb.toString());
		}
			 m.appendTail(sb);
			 System.out.println(sb.toString());
		}
}

輸出:

'Let the cat come out of the bag'.To disclose a secret(cat)**

例子3

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

public class MatcherAppendReplacementExample3 {

	public static void main(String[] args) {

		//pattern/expression to be matched
				Pattern p = Pattern.compile("[1-9]+");
				//Regular expression
				 Matcher m = p.matcher("131Hello232word7876");
				 // Creating the target string buffer
				 StringBuffer sb = new StringBuffer();
				 while (m.find()) {
				     m.appendReplacement(sb, "-");//calling method 
				     System.out.println("Start: "+m.start()+" End:"+m.end());
				 }
				 m.appendTail(sb);
				 System.out.println(sb.toString());
			}
		}

輸出:

Start: 0 End:3
Start: 8 End:11
Start: 15 End:19
-Hello-word-




相關用法


注:本文由純淨天空篩選整理自 Java Matcher appendReplacement() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。