+ Start a Discussion
Scott.MScott.M 

String.replaceFirst escape control characters in replacement string

I'm using String.replaceFirst to replace a token with an unkown string. I've run into an issue where the unknown string contained a back reference sequence $1. I don't wnat this to be interepreted as a back reference. An execption gets thrown since the group doesn't exist. My solution is to escape the $ character which works:

unknownString.replace('$', '\\$');

Is there a better way to escape control characters from the replacement string?  
James LoghryJames Loghry
Don't think there's a better way, no.  For what it's worth, the Apex regex syntax follows the Java regex syntax.  In other words, you can find a bunch of regular expression testers like this one http://www.regexplanet.com/advanced/java/index.html which may help if you'd like to play with regular expression syntax.