當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Matcher quoteReplacement(String)用法及代碼示例


Matcher類的quoteReplacement(String string)方法用於獲取作為參數傳遞的String的替換String文字。此String文字充當replace方法的參數。因此,quoteReplacement()方法充當替換方法的中間方法。

用法:

public static String quoteReplacement(String string)

參數:此方法采用參數字符串,該字符串是Matcher中要替換的String。


返回值:此方法返回一個字符串文字,它是匹配器的替換字符串。

下麵的示例說明Matcher.quoteReplacement()方法:

示例1:

// Java code to illustrate quoteReplacement() method 
  
import java.util.regex.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the regex to be checked 
        String regex = "Geek"; 
  
        // Create a pattern from regex 
        Pattern pattern = Pattern.compile(regex); 
  
        // Get the String to be matched 
        String 
            stringToBeMatched 
            = "GeeksForGeeks Geeks for For Geeks Geek"; 
  
        // Create a matcher for the input String 
        Matcher matcher 
            = pattern 
                  .matcher(stringToBeMatched); 
  
        // Get the String to be replaced 
        String stringToBeReplaced = "Geeks"; 
  
        // Get the String literal 
        // using quoteReplacement() method 
        System.out.println( 
            matcher 
                .quoteReplacement(stringToBeReplaced)); 
    } 
}
輸出:
Geeks

示例2:

// Java code to illustrate quoteReplacement() method 
  
import java.util.regex.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the regex to be checked 
        String regex = "FGF"; 
  
        // Create a pattern from regex 
        Pattern pattern 
            = Pattern.compile(regex); 
  
        // Get the String to be matched 
        String 
            stringToBeMatched 
            = "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF"; 
  
        // Create a matcher for the input String 
        Matcher matcher 
            = pattern.matcher(stringToBeMatched); 
  
        // Get the String to be replaced 
        String stringToBeReplaced = "GFG"; 
  
        // Get the String literal 
        // using quoteReplacement() method 
        System.out.println( 
            matcher 
                .quoteReplacement(stringToBeReplaced)); 
  
        System.out.println( 
            matcher 
                .replaceAll( 
                    matcher 
                        .quoteReplacement( 
                            stringToBeReplaced))); 
    } 
}
輸出:
GFG
GGFGGGFGGGFGGGFGGFG GFG GFG GFG GFG

參考: Oracle Doc



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Matcher quoteReplacement(String) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。