Java Regular Expression throws StackOverflow Exception

Discussion in 'Java' started by sravan, Sep 3, 2004.

  1. sravan

    sravan Guest

    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
     
    sravan, Sep 3, 2004
    #1
    1. Advertisements

  2. sravan

    Paul Lutus Guest

    Never, ever cross-post. Your inquiry has been answered. Go find the reply.
     
    Paul Lutus, Sep 3, 2004
    #2
    1. Advertisements

  3. sravan

    Alan Moore Guest

    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);
     
    Alan Moore, Sep 3, 2004
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.