Javascript正则表达式导致浏览器挂起

时间:2014-01-27 22:44:59

标签: javascript regex google-chrome pattern-matching

我正在尝试用正则表达式解析堆栈跟踪,但似乎它有一些主要的性能问题,或者更糟糕的错误。当我在代码中运行时,浏览器似乎永远挂起,当我在控制台中运行时,它可能需要10或15秒才能返回。我正在测试铬。

以下是一个例子:

"Object.printStackTrace.implementation.createException (file:///F:/billysFile/code/javascript/nodejs/deadunit/browserPackage/deadunit.browser.gen.umd.js:942:19)"
  .match(/^(((new )?[a-zA-Z_$][\w$]*(.[a-zA-Z_$][\w$]*)*)\(\)@((?:http|https|file):\/\/[^\s)]+|javascript:.*)(:(\d*):(\d*))|((new )?[a-zA-Z_$][\w$]*(.[a-zA-Z_$][\w$]*)*) \(((?:http|https|file):\/\/[^\s)]+|javascript:.*)(:(\d*):(\d*))\)|((new )?[a-zA-Z_$][\w$]*(.[a-zA-Z_$][\w$]*)*) (\(native\)))$/)

这是构成之前的原始正则表达式:

"Object.printStackTrace.implementation.createException (file:///F:/billysFile/code/javascript/nodejs/deadunit/browserPackage/deadunit.browser.gen.umd.js:942:19)".match(CHROME_STACK_LINE)

var IDENTIFIER_PATTERN_ = '[a-zA-Z_$][\\w$]*';
var URL_PATTERN_ = '((?:http|https|file)://[^\\s)]+|javascript:.*)';

var CHROME_FILE_AND_LINE = URL_PATTERN_+'(:(\\d*):(\\d*))'
var CHROME_COMPOUND_IDENTIFIER = "((new )?"+IDENTIFIER_PATTERN_+'(\\.'+IDENTIFIER_PATTERN_+')*)'

var CHROME_ANONYMOUS_FUNCTION = CHROME_COMPOUND_IDENTIFIER+'\\(\\)'+'@'+CHROME_FILE_AND_LINE
var CHROME_NORMAL_FUNCTION = CHROME_COMPOUND_IDENTIFIER+' \\('+CHROME_FILE_AND_LINE+'\\)'
var CHROME_NATIVE_FUNCTION = CHROME_COMPOUND_IDENTIFIER+' (\\(native\\))'

var CHROME_FUNCTION_CALL = '('+CHROME_ANONYMOUS_FUNCTION+"|"+CHROME_NORMAL_FUNCTION+"|"+CHROME_NATIVE_FUNCTION+')'
var CHROME_STACK_LINE = new RegExp('^'+CHROME_FUNCTION_CALL+'$')

我在这里做了一些可怕的错事吗?它看起来不像catastrophic backtracing ..

1 个答案:

答案 0 :(得分:1)

这个( . [a-zA-Z_$] [\w$]* )*点存在一个主要问题 可能会将其更改为\.

这是你扩展的正则表达式 获取RegexFormat4之类的工具来查看您的身份 大正则表达式。

 ^
 (
      (
           ( new\  )?
           [a-zA-Z_$] [\w$]* 
           ( . [a-zA-Z_$] [\w$]* )*
      )
      \(\)@
      (
           (?: http | https | file )
           :// [^\s)]+ 
        |  javascript: .* 
      )
      (
           :
           ( \d* )
           :
           ( \d* )
      )
   |  (
           ( new\  )?
           [a-zA-Z_$] [\w$]* 
           ( . [a-zA-Z_$] [\w$]* )*
      )
      \ \(
      (
           (?: http | https | file )
           :// [^\s)]+ 
        |  javascript: .* 
      )
      (
           :
           ( \d* )
           :
           ( \d* )
      )
      \)
   |  (
           ( new\  )?
           [a-zA-Z_$] [\w$]* 
           ( . [a-zA-Z_$] [\w$]* )*
      )
      \ 
      ( \(native\) )
 )
 $