import java.util.regex.Matcher; import java.util.regex.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 = Pattern.compile(patt); Matcher m = r.matcher(input); System.out.println("ReplaceAll:" + m.replaceAll("favour")); // appendReplacement方法 m.reset(); StringBuffer sb = new StringBuffer(); while (m.find()) { // 將匹配之前的字串複製到sb,再將匹配結果替換為:"favour",並追加到sb m.appendReplacement(sb, "favour"); } System.out.println(sb.toString()); m.appendTail(sb); System.out.println(sb.toString()); } }
輸出:
Input:Do me a favor? Fetch my favorites.AAA favor BBB 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