You need to sign in to do that
Don't have an account?
Shailesh Deshpande
Problems with String.replaceAll
Hi,
I have a String as '[!TEST!]' . Now I wish to replace this string with some other string say "SFDC". I am not able to do so.
I am using the String.replaceAll() function.
Below is a eg:
String str = 'Hi! How aRE YOU? I hope you are fine. D.';
str = str.replaceAll('[!Test!]','SFDC' );
system.debug(str);
Now this code replaces exclamation, T, e, s , t with SFDC. i.e the output is:
HiSFDC How aRE YOU? I hopSFDC you arSFDC finSFDC. D
which i am not expecting.
How can i replace this entire string .i.e [!Test!]
Thanks,
Shailesh.
I think the problem is that the string you are trying to replace "[!Test!]" is surrounded by brackets, and in Java regular expression syntax this matches any character inside the brackets and not the entire string. So you are replacing any character in the input that is one of (!,T,e,s,t) with SFDC.
It should work fine if you escape the brackets:
String str = 'Hi! How aRE YOU? [!Test!] I hope you are fine. D.';
str = str.replaceAll('\\[!Test!\\]','SFDC' );
system.debug(str);
Java pattern syntax is explained here: http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html
This is linked in the Apex docs: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm
All Answers
Hello shailesh,
have you tried this:
Output of above code is :
Hi! How aRE YOU? SFDC I hope you are fine. D. SFDC
Hope it helps. :)
I think the problem is that the string you are trying to replace "[!Test!]" is surrounded by brackets, and in Java regular expression syntax this matches any character inside the brackets and not the entire string. So you are replacing any character in the input that is one of (!,T,e,s,t) with SFDC.
It should work fine if you escape the brackets:
String str = 'Hi! How aRE YOU? [!Test!] I hope you are fine. D.';
str = str.replaceAll('\\[!Test!\\]','SFDC' );
system.debug(str);
Java pattern syntax is explained here: http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html
This is linked in the Apex docs: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm