Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaMatcher quoteReplacement(String) method in Java with Examples

Matcher quoteReplacement(String) method in Java with Examples

The quoteReplacement(String string) method of Matcher Class is used to get the replacement String literal of the String passed as parameter. This String literal acts as the parameter for the replace methods. Hence quoteReplacement() method acts as the intermediate in the replace methods.

Syntax:

public static String quoteReplacement(String string)

Parameters: This method takes a parameter string which is the String to be replaced in the Matcher.

Return Value: This method returns a String literal which is the replacement String for the matcher.

Below examples illustrate the Matcher.quoteReplacement() method:

Example 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));
    }
}


Output:

Geeks

Example 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)));
    }
}


Output:

GFG
GGFGGGFGGGFGGGFGGFG GFG GFG GFG GFG

Reference: Oracle Doc

RELATED ARTICLES

Most Popular

Recent Comments