[SalesForce] “Maximum stack depth reached: 3” when doing String.replaceAll()

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?!

Best Answer

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:

'/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/'
'(//.*)|\'.*\''

And making two passes on sourceCode.

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