I got StackOverflowError
when matching the result using a RegEx pattern.
The pattern is (d*?(;(?=d))?)+
. This regex is used to validate the input:
12345;4342;234*;123*;344324
The input is a string consists of values (only digits) separated by ;
. Each value could include one *
at the end (used as wildcard for other matching). There is no ;
at the end of the string.
The problem is that this regex works fine which small number of values. But when the numbers of values is too large (over 300), it will cause StackOverflowError
.
final String TEST_REGEX = "(\d\*?(;(?=\d))?)+";
// Generate string
StringBuilder builder = new StringBuilder();
int number = 123456;
for (int count = 1; count <= 300; count++) {
builder.append(Integer.toString(number).concat(";"));
number++;
}
builder.deleteCharAt(builder.lastIndexOf(";"))
builder.toString().matches(TEST_REGEX); //<---------- StackOverflowError
And the stacktrace:
java.lang.StackOverflowError
at java.util.regex.Pattern$BmpCharProperty.match(Pattern.java:3715)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4556)
at java.util.regex.Pattern$Loop.match(Pattern.java:4683)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4615)
at java.util.regex.Pattern$Ques.match(Pattern.java:4079)
at java.util.regex.Pattern$Ques.match(Pattern.java:4079)
at java.util.regex.Pattern$BmpCharProperty.match(Pattern.java:3715)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4556)
at java.util.regex.Pattern$Loop.match(Pattern.java:4683)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4615)
at java.util.regex.Pattern$Ques.match(Pattern.java:4079)
at java.util.regex.Pattern$Ques.match(Pattern.java:4079)
at java.util.regex.Pattern$BmpCharProperty.match(Pattern.java:3715)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4556)
at java.util.regex.Pattern$Loop.match(Pattern.java:4683)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4615)
...
I think the lookahead in the pattern cause this error since there are lots of lookup but I haven't figured out how to reduce it or work around.
I really appreciate any suggestion since I'm not experienced in RegEx.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…