Ross J
Ross J

Reputation: 382

Replace specific character with escaped version in Java

I have a large String with many occurrences like this:

List<String>

I need to convert that String so that it matches

List\<String\>

I was assuming that I would use the Java replaceAll("", "") method but I can't get it to work as I am not all that familiar with Regular expressions.

Any help would be appreciated

Upvotes: 0

Views: 111

Answers (1)

M A
M A

Reputation: 72874

You need four backslash characters, e.g.:

String input = "List<String>";
input = input.replaceAll("<", "\\\\<").replaceAll(">", "\\\\>");

"\\\\<" is the string literal for specifying \\<.

But why 2 \ are necessary in the replacement string? Since the replacement string itself also has escape syntax (to escape $, which is used for specifying content in capturing group). \< (or as string literal "\\<") is interpreted as < by the replace method. So we need to escape the \ character at the replacement string level.

Upvotes: 2

Related Questions