Search code examples
javaregexstringbuffer

What do they mean with the following sentence:


From this java API:

Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

I get the first bit, However a little confuse about the part underscored in bold. What do they mean with "to escape literal characters"? what kind of literal characters would you escape in a replacement string?

Thanks in advance.


Solution

  • Well, the $ ;)

    public static void main(final String... args)
    {
        final Pattern p = Pattern.compile("one dollar");
    
        final String input = "I want one dollar, please";
    
        // IndexOutOfBoundsException: no group 1
        System.out.println(p.matcher(input).replaceFirst("$1"));
        // You need to escape the "$"
        System.out.println(p.matcher(input).replaceFirst("\\$1"));
    }