+ Start a Discussion

Problem in Replaceall in string Method

My code:

ss= (ss!= '' && ss!= null) ? ss.replaceAll('[$^]','[$|^]') : '';


My input:

^Hospitality$^Hospitality$^Industrial / Office Flex$^Industrial$^Industrial Condos$^Industrial/Warehouse$^Hospitality$


I got the following error:


Illegal group reference (Invalid replacement string: '[$|^]'. '$' should be escaped if you do not intend to use a backreference. Try using Matcher.quoteReplacement() for your argument)


I am using matcher 


Pattern nonWordChar = Pattern.compile('[\\$|^]');
ss = nonWordChar.matcher(ss).replaceAll('');


But its not working





In replaceall method the backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if the string was treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences, and backslashes are used to escape literal characters in the replacement string.Invoking this method changes this Matcher object's state.


If the Matcher object is to be used in further matching operations it should first be reset.Given the regular expression a*b, the input "aabfooaabfooabfoob", and the replacement string"-", an invocation of this method on a Matcher object for that expression would yield the string "-foo-foo-foo-". quoteReplacement: Returns a literal replacement string for the specified string s. The characters in the returned string match the sequence of characters in s. Metacharacters (such as $ or ^) and escape sequences in the input string are treated as literal characters with no special meaning.


Reference: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_pattern_and_matcher_matcher_methods.htm


Hope this helps!