I have a requirement where I need to format 'Phone Number' field which is of type 'Phone'. It should not allow some of the special characters like %$#@*&, so am trying to replace each character individually with blank as below but it's acting weird. Am using the expression as below to replace everything except alphanumeric values and the 2 characters ( & ).

Acc.Phone = Acc.Phone.replaceAll('[^\\(\\)][^a-zA-Z0-9]','');

And when I entered


Its formatted as




formatted as


If someone understand what's happening and where am doing the mistake, please correct me.



The problem is that you're using two character sets (a set starts with [ and ends with ]).

In your first example, the first match happens in the bold area:


Because 6 matches [^\\(\\)] (it is not a parentheses), and * matches [^a-zA-Z0-9] (it is not a letter or number).

The next match occurs here:


Because 8 matches [^\\(\\)], and ( matches [^a-zA-Z0-9].

You can see that by trying to match two sets, you're actually matching a more complex pattern than you meant to.

Instead, you want one character set, and you can use + to indicate one or more occurrences (better performance):

Acc.Phone = Acc.Phone.replaceAll('[^\\(\\)a-zA-Z0-9]+','');
  • Thanks a lot, i got the concept now. But, to match every special character, do we need to prefix with \\? for example, replaceAll('[^\*\\&a-zA-Z0-9]+',''); is not working as expected. – Amulya Apr 4 '16 at 15:12
  • 1
    @Amulya Actually, no, you don't need to escape special characters like (, ), , |, and so on *within a character set (but, of course, [ and ] should be escaped). Also note that you need to use \\ to represent a single escape, and \\\\ to represent an actual backslash character. This is because the parser/compiler converts \\ into a literal \. – sfdcfox Apr 4 '16 at 16:15
    Hi Please try this regular expression to remove special character from   phone field 
    e.g :

    String strName = 'aZ^96*85/56+9^8(45)874*56^8(';
    String replacement = '[*/+()^a-zA-Z]';
    String result = strName.replaceALL(replacement,'');
    System.debug('Result ::'+result);

    Result will be : 9685569845874568
  • Hi Sagar, No this expression doesn't work. According to [*/+()^a-zA-Z], it should not replace alphabets right, but in your results, no alphabets at all. – Amulya Apr 4 '16 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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