0
Pattern eqPattern = Pattern.compile("(.*?)([a-z0-9\\_\\.]*) eq \"(((\\\\\")|[^\"])*)\"([\\s]*.*)", Pattern.CASE_INSENSITIVE);

This is my regex. When I try to match a long string, I got stack overflow. The pattern will match something like column1 eq "abc" and column ne "abc"; (\\\")|[^\"]): to skip " in inside "". I want to ask how to rewrite this to prevent stack overflow.

3
  • What would be the sample that overflows ? Commented Nov 4, 2019 at 22:11
  • The test case is long and I cant give it here. Something like . user eq "1200 repeated s" Commented Nov 4, 2019 at 22:19
  • No problem, probably a bunch of escaped stuff. Commented Nov 4, 2019 at 22:20

1 Answer 1

2

The best approach is to remove the alternation from the regex.
That can be done like this, which uses the unrolled loop instead:

"(.*?)([\\w.]*) eq \"([^\"\\\\]*(?:\\\\[\\S\\s][^\"\\\\]*)*)\"(\\s*.*)"

Raw and Expanded

 ( .*? )                       # (1)
 ( [\w.]* )                    # (2)
 [ ] eq [ ] 
 "
 (                             # (3 start)
      [^"\\]* 
      (?:

           \\ [\S\s] 
           [^"\\]* 
      )*
 )                             # (3 end)
 "
 ( \s* .* )                    # (4)
Sign up to request clarification or add additional context in comments.

2 Comments

Great. It works. Can you please give some explanation of ([^\"\\\]*(?:\\\[\\S\\s][^\"\\\]*)*)? Quite hard to understand.
Sure. This optional clause [^"\\]* matches non escapes nor quotes greedily. In the last part which is optional, there can only be an escape anything which is required, followed by the optional clause again [^"\\]* where these are wrapped into a repeating optional group. The result is that there is no need for an alternation, in which Java executes on the stack. In the original regex, the first check was an escape anything which probably sent it to the alternation a lot. You probably could get away with this as well "((?:[^"\\]|\\[\S\s])*)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.