# How to replace the special character from the string in Apex [duplicate]

We need to remove the all special character from the string in apex.

String s1 = 'a"b*c:5>x<y?z/de|f\'';
String regExp = '"*:<>?\/|\/‘;
String replacement = '1';
String s2 = s1.replaceAll(regExp, replacement);
System.debug(s2);


Above code shows,

Illegal string literal: Invalid string literal '"*:<>\/?|'. Illegal character sequence \/' in string literal error.

How to remove the special character from the string in apex.

If you want to include a character like backslash, you need to escape it.

'abc\def'


Use:

'abc\\def'


That will compile, but you have another problem. Your current approach searches for all the characters in sequence. You need to define a set of values using square brackets ([...]).

That said, if you want to remove non-alphanumeric text (aside from whitespace), you can use a simpler expression:

String regExp = '[^\\w\\s]';


What this expression says is find any single character which is not a word character or whitespace.

• \\w includes underscore as well, just something for others to keep in mind. Feb 13, 2018 at 15:10
• @DerekF Indeed but the OP is not trying to replace underscores, so I didn't call that out specifically. Feb 13, 2018 at 15:12