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


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


該方法用於實現終端append-and-replace 步驟。此方法從輸入序列中讀取字符,從替換的追加位置開始,並將它們追加到給定的字符串緩衝區。

用法

public StringBuffer appendTail(StringBuffer strbuff)

參數

strbuff- 目標字符串緩衝區

返回

目標字符串緩衝區

例子1

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

public class MatcherAppendTailExample1 {

	public static void main(String[] args) {
		
//pattern/expression to be matched
		Pattern p = Pattern.compile("a+");
		//Regular expression
		 Matcher m = p.matcher(" 13aaa08aaa2018 ");
		 // Creating the target string buffer
		 StringBuffer sb = new StringBuffer();
		 while (m.find()) {
		     m.appendReplacement(sb, "-");//calling method
		 }
		 // Appending the string buffer to the end 
		 m.appendTail(sb);
		 //converting String Buffer to String
		 System.out.println(sb.toString());
}
}

輸出:

13-08-2018 

例子2

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

public class MatcherAppendTailExample2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//pattern/expression to be matched
		Pattern p = Pattern.compile("a+");
		//Regular expression
		 Matcher m = p.matcher(" 13aaa08aaa2018 ");
		 
		 // Creating the target string buffer
		 StringBuffer sb = new StringBuffer();
		 while (m.find()) {
			 m.appendReplacement(sb,"-" );
			 System.out.println(" start:"+m.start()+", End:"+m.end());
		}
		 // Appending the string buffer to the end 
		 m.appendTail(sb);
		 //converting String Buffer to String
		 System.out.println("After Replacing Matching position:"+sb.toString());
	}
}

上述程序的輸出

 start:3, End:6
 start:8, End:11
 After Replacing Matching position:13-08-2018 




相關用法


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