Java SE API

Matcher.quoteReplacement()

Return a replacement string treating input literally. Java SE API; example uses Java 21-compatible syntax.

Formal Syntax & Structure

java syntaxjava
static String quoteReplacement(String s)

Parameters & Attributes

NameTypeDescription
sStringLiteral replacement

Return Value

String

Return a replacement string treating input literally.

Working Example

Example Snippetjava
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main {    public static void main(String[] args) throws Exception {        String needle = "a.b";        String value = "$5";        String input = "a.b axb a.b";        System.out.println(Pattern.compile(Pattern.quote(needle)).matcher(input).replaceAll(Matcher.quoteReplacement(value)));        System.out.println(input.replace(needle, value));    }}
Java Reference