Java经典实例:正则表达式,替换匹配的⽂本import Matcher;
import Pattern;
/**
* Created by Frank
* 替换匹配的⽂本
*/
public class ReplaceDemo {
public static void main(String[] args) {
// 创建⼀个正则表达式模式,⽤以匹配⼀个单词(\b=单词边界)
String patt = "\\bfavor\\b";
// ⽤于测试的输⼊字符串
String input = "Do me a favor? Fetch my favorites.AAA favor BBB";
System.out.println("Input:" + input);
// 从正则表达式实例中运⾏⽅法并查看其如何运⾏
Pattern r = Patternpile(patt);
Matcher m = r.matcher(input);
System.out.println("ReplaceAll:" + m.replaceAll("favour"));
// appendReplacement⽅法
StringBuffer sb = new StringBuffer();
while (m.find()) {
// 将匹配之前的字符串复制到sb,再将匹配结果替换为:"favour",并追加到sb
m.appendReplacement(sb, "favour");
}
System.out.String());
m.appendTail(sb);
System.out.String());
}
}
输出:
Input:Do me a favor? Fetch my favorites.AAA favor BBBreplaceall()
ReplaceAll:Do me a favour? Fetch my favorites.AAA favour BBB
Do me a favour? Fetch my favorites.AAA favour
Do me a favour? Fetch my favorites.AAA favour BBB

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。