简体   繁体   English

如何使这个正则表达式不会导致“灾难性的回溯”?

[英]How can I make this regular expression not result in “catastrophic backtracking”?

I'm trying to use a URL matching regular expression that I got from http://daringfireball.net/2010/07/improved_regex_for_matching_urls 我正在尝试使用我从http://daringfireball.net/2010/07/improved_regex_for_matching_urls获得的匹配正则表达式的URL

(?xi)
\b
(                       # Capture 1: entire matched URL
  (?:
    https?://               # http or https protocol
    |                       #   or
    www\d{0,3}[.]           # "www.", "www1.", "www2." … "www999."
    |                           #   or
    [a-z0-9.\-]+[.][a-z]{2,4}/  # looks like domain name followed by a slash
  )
  (?:                       # One or more:
    [^\s()<>]+                  # Run of non-space, non-()<>
    |                           #   or
    \(([^\s()<>]+|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
  )+
  (?:                       # End with:
    \(([^\s()<>]+|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
    |                               #   or
    [^\s`!()\[\]{};:'".,<>?«»“”‘’]        # not a space or one of these punct chars
  )
)

Based on the answers to another question , it appears that there are cases that cause this regex to backtrack catastrophically . 根据另一个问题的答案,似乎有些案例导致这个正则表达式灾难性回溯 For example: 例如:

var re = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
re.test("http://google.com/?q=(AAAAAAAAAAAAAAAAAAAAAAAAAAAAA)")

... can take a really long time to execute (eg in Chrome) ...可能需要很长时间才能执行(例如在Chrome中)

It seems to me that the problem lies in this part of the code: 在我看来,问题在于这部分代码:

(?:                       # One or more:
    [^\s()<>]+                  # Run of non-space, non-()<>
    |                           #   or
    \(([^\s()<>]+|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
  )+

... which seems to be roughly equivalent to (.+|\\((.+|(\\(.+\\)))*\\))+ , which looks like it contains (.+)+ ......似乎大致相当于(.+|\\((.+|(\\(.+\\)))*\\))+ ,看起来它包含(.+)+

Is there a change I can make that will avoid that? 我可以做出改变以避免这种情况吗?

Changing it to the following should prevent the catastrophic backtracking: 将其更改为以下内容可以防止灾难性的回溯:

(?xi)
\b
(                       # Capture 1: entire matched URL
  (?:
    https?://               # http or https protocol
    |                       #   or
    www\d{0,3}[.]           # "www.", "www1.", "www2." … "www999."
    |                           #   or
    [a-z0-9.\-]+[.][a-z]{2,4}/  # looks like domain name followed by a slash
  )
  (?:                       # One or more:
    [^\s()<>]+                  # Run of non-space, non-()<>
    |                           #   or
    \(([^\s()<>]|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
  )+
  (?:                       # End with:
    \(([^\s()<>]|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
    |                               #   or
    [^\s`!()\[\]{};:'".,<>?«»“”‘’]        # not a space or one of these punct chars
  )
)

The only change that was made was to remove the + after the first [^\\s()<>] in each of the "balanced parens" portions of the regex. 唯一的变化是在正则表达式的每个“平衡的parens”部分中删除第一个[^\\s()<>]之后的+

Here is the one-line version for testing with JS: 以下是使用JS进行测试的单行版本:

var re = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
re.test("http://google.com/?q=(AAAAAAAAAAAAAAAAAAAAAAAAAAAAA")

The problem portion of the original regex is the balanced parentheses section, to simplify the explanation of why the backtracking occurs I am going to completely remove the nested parentheses portion of it because it isn't relevant here: 原始正则表达式的问题部分是平衡括号部分,以简化回溯发生原因的解释我将完全删除它的嵌套括号部分,因为它在这里不相关:

\(([^\s()<>]+|(\([^\s()<>]+\)))*\)    # original
\(([^\s()<>]+)*\)                     # expanded below

\(                # literal '('
(                 # start group, repeat zero or more times
    [^\s()<>]+        # one or more non-special characters
)*                # end group
\)                # literal ')'

Consider what happens here with the string '(AAAAA' , the literal ( would match and then AAAAA would be consumed by the group, and the ) would fail to match. At this point the group would give up one A , leaving AAAA captured and attempting to continue the match at this point. Because the group has a * following it, the group can match multiple times so now you would have ([^\\s()<>]+)* matching AAAA , and then A on the second pass. When this fails an additional A would be given up by the original capture and consumed by the second capture. 考虑一下这里发生的字符串'(AAAAA' ,文字(将匹配然后AAAAA将由该组消费,并且)将无法匹配。此时该组将放弃一个A ,留下AAAA捕获并且此时尝试继续比赛。由于该组有一个*跟随它,该组可以匹配多次,所以现在你可以([^\\s()<>]+)*匹配AAAA ,然后A第二次通过。当这次失败时,额外的A将被原始捕获放弃并被第二次捕获消耗。

This would go on for a long while resulting in the following attempts to match, where each comma-separated group indicates a different time that the group is matched, and how many characters that instance matched: 这将持续很长时间,导致以下尝试匹配,其中每个逗号分隔的组指示组匹配的不同时间,以及实例匹配的字符数:

AAAAA
AAAA, A
AAA, AA
AAA, A, A
AA, AAA
AA, AA, A
AA, A, AA
AA, A, A, A
....

I may have counted wrong, but I'm pretty sure it adds up to 16 steps before it is determined that the regex cannot match. 我可能算错了,但我确定它在确定正则表达式无法匹配之前最多可增加16个步骤。 As you continue to add additional characters to the string the number of steps to figure this out grows exponentially. 当您继续向字符串添加其他字符时,计算出来的步骤数呈指数增长。

By removing the + and changing this to \\(([^\\s()<>])*\\) , you would avoid this backtracking scenario. 通过删除+并将其更改为\\(([^\\s()<>])*\\) ,您将避免此回溯方案。

Adding the alternation back in to check for the nested parentheses doesn't cause any problems. 重新添加交替以检查嵌套括号不会导致任何问题。

Note that you may want to add some sort of anchor to the end of the string, because currently "http://google.com/?q=(AAAAAAAAAAAAAAAAAAAAAAAAAAAAA" will match up to just before the ( , so re.test(...) would return true because http://google.com/?q= matches. 请注意,您可能希望在字符串的末尾添加某种锚点,因为目前"http://google.com/?q=(AAAAAAAAAAAAAAAAAAAAAAAAAAAAA"将匹配到(因此re.test(...)之前re.test(...)因为http://google.com/?q=匹配而返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM