当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。