-
Enhancement
-
Resolution: Not an Issue
-
P4
-
None
-
8u66
-
generic
-
generic
A DESCRIPTION OF THE REQUEST :
I was using a replacement string that contained regex special chars like '$', '\' , '&' that needed to be used literally. I used quoteReplacement on that string. The method did escape the '$\' chars but didn't escape the '&', so the replacement treated it as a regex variable and replace the whole string properly. While the doc clearly says that quoteReplacement escapes only '$\' - I had to use extra escaping for the '&' char.
JUSTIFICATION :
It would be nice to avoid an extra replaceAll on a string. If there is a method that is supposed to take care of escaping special chars then it should be all chars that are special for regex.
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
quoteReplacement should escape '&' as well as '$' and '\'. Possibly other special chars too.
ACTUAL -
quoteReplacement doesn't escape '&'.
---------- BEGIN SOURCE ----------
String s = "Dogs and cats are lovely pets but cost some money to see a vet"
s= s.replaceAll("money", Matcher.quoteReplacement("$")); // works
s= s.replaceAll("and", Matcher.quoteReplacement("&")); // doesn't
---------- END SOURCE ----------
CUSTOMER SUBMITTED WORKAROUND :
s= s.replaceAll("and", Matcher.quoteReplacement("\\\\&"));
I was using a replacement string that contained regex special chars like '$', '\' , '&' that needed to be used literally. I used quoteReplacement on that string. The method did escape the '$\' chars but didn't escape the '&', so the replacement treated it as a regex variable and replace the whole string properly. While the doc clearly says that quoteReplacement escapes only '$\' - I had to use extra escaping for the '&' char.
JUSTIFICATION :
It would be nice to avoid an extra replaceAll on a string. If there is a method that is supposed to take care of escaping special chars then it should be all chars that are special for regex.
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
quoteReplacement should escape '&' as well as '$' and '\'. Possibly other special chars too.
ACTUAL -
quoteReplacement doesn't escape '&'.
---------- BEGIN SOURCE ----------
String s = "Dogs and cats are lovely pets but cost some money to see a vet"
s= s.replaceAll("money", Matcher.quoteReplacement("$")); // works
s= s.replaceAll("and", Matcher.quoteReplacement("&")); // doesn't
---------- END SOURCE ----------
CUSTOMER SUBMITTED WORKAROUND :
s= s.replaceAll("and", Matcher.quoteReplacement("\\\\&"));