user5699936 user5699936 - 2 months ago 21
Java Question

Java: Regular Expression is causing stack overflow

I have java code and I want to parse C file and find all the comments.

In order to find all the comments that are line or lines that start with

/*
and end with
*/
I am using this Regular Expression:
Pattern.compile("/\\*(?:.|[\\n\\r]|[\\n])*?\\*/")


The problem is that some input is causing stack overflow.

I read about this problem and understood I shall avoid using
|
in the regex. I am new to the regex world. Can someone help me make it simpler?

Answer

Your linebreak handling is not correct.

Try to use this:

Pattern.compile("/\\*.*?\\*/", Pattern.MULTILINE|Pattern.DOTALL);

This enables your . character to match linebreaks as well.