java.time.Matcher.quoteReplacement(String s)方法

2019-10-16 22:19:16

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

宣告

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

public static String quoteReplacement(String s)

引數

  • s - 要文字化的字串。

返回值

文字字串替換。

範例

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

package com.yiibai;

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.