Java Regular Expression throws StackOverflow Exception

S

sravan

I was just trying to use a regular expression for finding me the
patterns which match

X(\\n|\\r|.)*? Y

What this means is to find the pattern which matches any String that
starts with X followed by any number of characters or new lines or new
carriage returns and finally followed by Y.

To summarize find the pattern which matches the block X ........ Y
which can be separated by any characters/newlines/tabs etc.

Ex:

X


AFJALFJA

Y

should be selected.

When i use the pattern shown above the java prog throws me
StackOverflow exception. Can you throw me some light into
pattern/expression modification??

Thanx
Sravan
 
P

Paul Lutus

sravan said:
I was just trying to use a regular expression for finding me the
patterns which match

Never, ever cross-post. Your inquiry has been answered. Go find the reply.
 
A

Alan Moore

I was just trying to use a regular expression for finding me the
patterns which match

X(\\n|\\r|.)*? Y
When i use the pattern shown above the java prog throws me
StackOverflow exception. Can you throw me some light into
pattern/expression modification??

Whenever you find yourself using alternation to match one character at
a time - e.g., (a|b|c) - you should use a character class instead -
[abc]. Alternation is hideously inefficient compared to character
classes (although you still shouldn't get stack overflows - ideally,
the Pattern class should optimize the regex as it compiles, but it's
not that sophisticated yet).

In this case, you don't even have to do that, because you can force
the dot to match line-separator characters with the DOTALL flag:

Pattern p = Pattern.compile("X.*?Y", Pattern.DOTALL);

....or you can use the inline version, (?s), which comes in handy if
you're using the convenience methods, like String#replaceAll():

str = str.replaceAll("(?s)X.*?Y", someOtherString);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top