haranadh
haranadh

Reputation: 59

Regex matching groups

I have an issue with replaceAll function of Java string

replaceAll("regex", "replacement");

works fine but whenever my "replacement" string contains the substring like "$0", "$1" .e.t.c, it will create problem by substituting these $x's with corresponding matching group.

For instance

input ="NAME";
input.replaceAll("NAME", "HAR$0I");

will result in a string "HARNAMEI" as the replacement string contains "$0" which will be substituted by matching group "NAME". How can I override that nature. I need to get the result string as "HAR$0I" only.

I escaped the $ .i.e I converted the replacement string to "HAR\\$0I" which worked fine. But I am looking for any method in java that will do this for me for all such characters which has special meaning in regex world.

Upvotes: 1

Views: 162

Answers (3)

SLaks
SLaks

Reputation: 888233

It sounds like you're actually trying to replace raw strings, without using regexes at all.

You should simply call String.replace(), which does literal replacements without using regexes.

Upvotes: 0

Pshemo
Pshemo

Reputation: 124275

$ in replacement is special character allowing you to use groups. To make it literal you will need to escape it with \$ which needs to be written as "\\$". Same rule apply for \, since it is special character used to escape $. If you would like to use \ literal in replacement you would also need to escape it with another \, so you would need to write it as \\\\.

To simplify this process you can just use Matcher.quoteReplacement("yourReplacement")).


In case where you don't need to use regular expression you can simplify it even more and use

replace("NAME", "HAR$0I") 

instead of

replaceAll("NAME", Matcher.quoteReplacement("HAR$0I")) 

Upvotes: 0

Aubin
Aubin

Reputation: 14883

The documentation of java.lang.String.replaceAll() says:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

The documentation of String quoteReplacement(String s) says:

Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.

Upvotes: 1

Related Questions