为什么这个正则表达式要花很多时间?^([a-zA-Z]+[0-9][-][^\s._^%$#!~@,])+$
Why does this regex take lot of time?^([a-zA-Z]+[0-9][-][^\s._^%$#!~@,])+$
这个正则表达式需要很多时间来匹配任何字符串。
要匹配的字符串 cbdvhuvffviuhwrevfnvfduvildouqjiofeqfelvimpupvcuipvhfjdvufhvfd,ofvhfuhffduisfdwfewdsiu
^([a-zA-Z]+[0-9]*[-]*[^\s._^%$#!~@,])+$
Rubular 停止工作。
Regular Expressions can be very expensive. Certain (unintended and intended) strings may cause RegExes to exhibit exponential behavior.
-- (from CodingHorror)
所谓的 catastrophic backtracking 当您有两组嵌套的变量匹配项可以匹配正则表达式中的相同内容时,就会发生这种情况。
特别是如果 inout 与正则表达式不匹配,引擎将在嵌套循环中检查组的所有组合,这可能需要相当长的时间。
基本上,正则表达式引擎将始终尝试在每个步骤中匹配尽可能多的字符,即使是可变组(即带有 +
、*
或 [=12= 的序列) ]).如果在某个时刻,输入字符串在没有完全匹配正则表达式的情况下结束,或者出现没有更多字符可以匹配当前组的情况,引擎将回溯。这意味着,它将 "unmatch" 一个字符并尝试找到一个解决方案,其中只有下一个变量组匹配该字符。
现在,在您的正则表达式中,您有一个嵌套的变量组。在这种情况下,引擎可以 运行 进入一个深层嵌套的循环,试图找到一个匹配的组合。这可能需要很长时间,因此有时可以用作 DoS 向量。
正则表达式引擎不是很聪明,工作规则非常简单(请参阅维基百科上的 Regular Language)。因此,他们通常不会自己检测这些循环,而是会愉快地合作,尝试所有组合。
The solution is simple. When nesting repetition operators, make absolutely sure that there is only one way to match the same match. If repeating the inner loop 4 times and the outer loop 7 times results in the same overall match as repeating the inner loop 6 times and the outer loop 2 times, you can be sure that the regex engine will try all those combinations.
这个正则表达式需要很多时间来匹配任何字符串。
要匹配的字符串 cbdvhuvffviuhwrevfnvfduvildouqjiofeqfelvimpupvcuipvhfjdvufhvfd,ofvhfuhffduisfdwfewdsiu
^([a-zA-Z]+[0-9]*[-]*[^\s._^%$#!~@,])+$
Rubular 停止工作。
Regular Expressions can be very expensive. Certain (unintended and intended) strings may cause RegExes to exhibit exponential behavior.
-- (from CodingHorror)
所谓的 catastrophic backtracking 当您有两组嵌套的变量匹配项可以匹配正则表达式中的相同内容时,就会发生这种情况。
特别是如果 inout 与正则表达式不匹配,引擎将在嵌套循环中检查组的所有组合,这可能需要相当长的时间。
基本上,正则表达式引擎将始终尝试在每个步骤中匹配尽可能多的字符,即使是可变组(即带有 +
、*
或 [=12= 的序列) ]).如果在某个时刻,输入字符串在没有完全匹配正则表达式的情况下结束,或者出现没有更多字符可以匹配当前组的情况,引擎将回溯。这意味着,它将 "unmatch" 一个字符并尝试找到一个解决方案,其中只有下一个变量组匹配该字符。
现在,在您的正则表达式中,您有一个嵌套的变量组。在这种情况下,引擎可以 运行 进入一个深层嵌套的循环,试图找到一个匹配的组合。这可能需要很长时间,因此有时可以用作 DoS 向量。
正则表达式引擎不是很聪明,工作规则非常简单(请参阅维基百科上的 Regular Language)。因此,他们通常不会自己检测这些循环,而是会愉快地合作,尝试所有组合。
The solution is simple. When nesting repetition operators, make absolutely sure that there is only one way to match the same match. If repeating the inner loop 4 times and the outer loop 7 times results in the same overall match as repeating the inner loop 6 times and the outer loop 2 times, you can be sure that the regex engine will try all those combinations.