Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am getting a strange "Maximum stack depth reached: 3" when doing a String.replaceAll() with bigger Regex on a quite big string (40 lines of text). I am trying to remove any comments and literal strings out of Apex Class source code.

private static final Pattern COMMENTS_LITERALS_PATTERN = Pattern.compile('(/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/)|(//.*)|\'.*\'');

String sourceCode = 'long text around 40';
String cleanedBody;

Matcher commentsLiteralsMatch = COMMENTS_LITERALS_PATTERN.matcher(original.Body);
if(commentsLiteralsMatch.find()) {
     cleanedBody = commentsLiteralsMatch.replaceAll('');     

But the small number 3 really looks to low for me to be any limit.

Do you have an explanation for this or did you experience similar behaviors?!

share|improve this question
Can you post the regex? – tomlogic Feb 18 '13 at 21:50
Sounds pretty strange, would help to create a case with Salesforce Support about this. – Ralph Callaway Feb 18 '13 at 23:57
tomlogic Sure sorry that I forgot to post a code example yesterday. – Robert Sösemann Feb 19 '13 at 13:21
This is still unsolved. I am searching comments and string literals in multiple ApexClass bodies and removing them by doing a replaceall(...,''); I run into Stack depth limits there. – Robert Sösemann Feb 20 '13 at 12:32

My guess is that you're reaching a limit on nested groups in your regular expression.

You could try splitting it into two separate match patterns:


And making two passes on sourceCode.

As for matching C-style comments, check out this Stack Overflow question.

share|improve this answer
Splitting the regex didn't work. Besides that it must be something different as in my code I have other regexps that have 10 and more groups. – Robert Sösemann Feb 19 '13 at 16:34
In the working regexps, are those groups nested three levels deep (((A))) or just lots of groups ((A)(B))(C)(D)((E)(F)) with less than three levels of nesting? – tomlogic Feb 19 '13 at 16:49
Oh now I understand. The 3 in the error message might come from 3 levels of groups?! You are right the others have a max grouping of 2. I try to rewrite the regexp with 3 levels. – Robert Sösemann Feb 19 '13 at 18:19

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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