本文由 ImportNew - 人晓 翻译自 ocpsoft。欢迎加入Java小组。转载请参见文章末尾的要求。
如果你处理过大量的正则表达式,那么你对“catastrophic backtracking”的概念一定不陌生,这种情况下处理器被强迫执行指数倍的计算。例如,点击该示例,看看它需要多久完成(应该在5-10秒后超时)。
LongRunningRegexExample.java
01
public class LongRunningRegexExample
02
{
03
public static void main(String[] args)throws InterruptedException
04
{
05
final Pattern pattern = Pattern.compile("(0*)*A");
06
final String input ="00000000000000000000000000";
07
08
long startTime = System.currentTimeMillis();
09
Matcher matcher = pattern.matcher(input);
10
matcher.find();// runs for a long time!
11
System.out.println("Regex took:" + (System.currentTimeMillis() - startTime) +&#