I Have a string like "Hello-how@are you!"

I want to get which special characters the string contains

I searched for an hour i able to get the thing like replacing the special characters

But i need to get which special character we have in a string.

Can anybody help me.

  • This sounds like more of a general programming/regular expression question than specific to Apex, which uses the Java reg exp engine.
    – Mike Chale
    Commented Feb 25, 2014 at 15:13

2 Answers 2


This code will find all special characters and output them to the debug log. It uses the ^ symbol which means not and the \w means any word character. We have to escape all \ with another .

String SPECIAL_CHAR_PATTERN = '[^\\w\\*]';
Pattern p = Pattern.compile(SPECIAL_CHAR_PATTERN);
Matcher pm = p.matcher('Hello-how@are you!');
while (pm.find()) {

This post should be pretty straight forward, and I would like to give it credit... https://stackoverflow.com/questions/13946651/matching-special-characters-and-letters-in-regex

Please take a look at Salesforce Pattern and Matcher Classes: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_pattern_and_matcher_pattern_methods.htm


Also it may be easier to do the opposite for matching... something like


I'm not a regular expression guy but this should be a good starting point.

Example of how your special character:

    Pattern myPattern = Pattern.compile('myRegularExpression');
    Matcher myMatch = myPattern.matcher('my custom string that I\'m searching');

    // loops till we reach the end of our group matches
    while (myMatch.find()) {    
        // pass our match to a string to manipulate
        String matchingPattern = myMatch.group();
        system.debug('Special character found: ' + matchingPattern);
  • It gives that string has special character or not. but i need to get that special character
    – Sunny
    Commented Feb 26, 2014 at 4:50
  • Yes, matcher will give you the special character. Please take a look at the answer as I have posted an example.
    – Double A
    Commented Feb 26, 2014 at 14:06

You must log in to answer this question.

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