java.util.regex.Matcher.replaceAll(String replacement)示例

java.util.regex.Matcher.replaceAll(String replacement)方法将替换与给定替换字符串的模式匹配的输入序列的每个子序列。

声明

以下是java.util.regex.Matcher.replaceAll(String replacement)方法的声明。

public String replaceAll(String replacement)

参数

  • replacement - 替换字符串。

返回值

通过用替换字符串替换每个匹配的子序列来构造的字符串,根据需要替换捕获的子序列。

示例

以下示例显示了java.util.regex.Matcher.replaceAll(String replacement)方法的用法。

package com.zaixian;

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

public class MatcherDemo {
   private static String REGEX = "dog";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);

      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      INPUT = matcher.replaceAll(REPLACE);
      System.out.println(INPUT);
   }
}

编译并运行上面的程序,这将产生以下结果 -

The cat says meow All cats say meow.

上一篇: Java正则表达式Matcher类 下一篇: Java正则表达式PatternSyntaxException类