0

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.

2

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

Instead of:

'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.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.