0

I am trying to replace all characters expect below mention characters with space in Apex [A-Z a-z 0-9-,.&/'@()+# $: ]

String customerName = jo&hn<>ji'o;
String AccName = customerName.replaceAll('[^0-9a-zA-Z\\&.,'-/@+():$#]',' ');
system.debug('AccName' + AccName);

But when I am trying to add single quote ' in the regex I am getting error. can anyone help me on this issue.

Thanks In Advance!!

1 Answer 1

3

Since Apex uses single quotes for string literals, anywhere that you need to use a single quote you need to escape it.

In many other languages, you'd just use a single backslash (i.e. \')
In Apex though, you need to use two backslashes (\\').

Apex treats a single backslash as the start of an "escape sequence". \n is the most common one, which tells Apex to replace those two characters with a line break. It's used to print ASCII characters that are "unprintable".

Since \' is not a valid escape sequence, we need to tell Apex to not treat it as an escape sequence. That's the function of the second backslash.

You must log in to answer this question.

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