1

We are trying to do a replacement of String in code particular for masking. In the code, we want to use replaceFirst to replace the first match. But instead of using regex, we want to use the actual string, something like below:

input = input.replaceFirst(stringToMask, masked);

This works in most situations, but in cases where the input string has a () in it, Salesforce will consider the input string to be a regex and try to resolve it will most probably cause an exception.

Is there a way we can escape the string here to make it to treat it as an normal string here? Otherwise we might need to go through the indexOf and subString() path.

1 Answer 1

4

You can use it "nearly" normally by quoting the area to use literally, which is done with \Q and \E.

String stringToMask = '(hello)';
stringToMask = '\\Q'+stringToMask+'\\E';

String stringToSearch = '(hello) this, (hello) that';
System.debug(stringToSearch.replaceFirst(stringToMask, 'goodbye'));

The only downside that I'm not sure how to work around is that a \E anywhere in the string will break; you might have to just remove them entirely.

However, this solution appears to work for all manner of "normal" regex characters, including brackets, curly brackets, asterisks, plus and minus signs, parentheses, etc.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .