static String quoteReplacement(String s)

优质
小牛编辑
129浏览
2023-12-01

描述 (Description)

java.time.Matcher.quoteReplacement(String s)方法返回指定String的文字替换String。

声明 (Declaration)

以下是java.time.Matcher.quoteReplacement(String s)方法的声明。

public static String quoteReplacement(String s)

参数 (Parameters)

  • s - 要文字化的字符串。

返回值 (Return Value)

文字字符串替换。

例子 (Example)

以下示例显示了java.time.Matcher.quoteReplacement(String s)方法的用法。

package cn.xnip;
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); 
      try{
         //Below line will throw exception
         INPUT = matcher.replaceAll(REPLACE);
      } catch(Exception e){
         System.out.println("Exception: "+ e.getMessage());
      }
      INPUT = matcher.replaceAll(matcher.quoteReplacement(REPLACE));
      System.out.println(INPUT);
   }
}

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

Exception: Illegal group reference: group index is missing
The cat$ says meow All cat$s say meow.