function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shailesh DeshpandeShailesh 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.

Best Answer chosen by Admin (Salesforce Developers) 
tharristharris

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

Rahul SharmaRahul Sharma

Hello shailesh,

 

have you tried this:

 

String str = 'Hi! How aRE YOU? [!Test!] I hope you are fine. D. [!Test!]';
string str1 = '[!Test!]';
str = str.replace(str1,'SFDC' );
system.debug(str);

 Output of above code is :

 

Hi! How aRE YOU? SFDC I hope you are fine. D. SFDC

 

Hope it helps. :)

tharristharris

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

 

This was selected as the best answer