2016-01-25 55 views
2

我使用Apache regexp作爲庫來驗證正則表達式。我想知道如何跟蹤一些正則表達式是否會導致災難性的回溯。 我想知道的是,是否有一些技巧來捕捉導致災難性回溯的正則表達式和字符串值? 我在RE.java類中嘗試了一些修改,但並不像預期的那樣。如何跟蹤正則表達式中的災難性回溯?

這是我的修改:

public RE(String pattern) throws RESyntaxException 
{ 
    this(pattern, MATCH_NORMAL); 
    paramString = pattern; 
} 


public RE(String pattern, int matchFlags) throws RESyntaxException 
{ 
    this(new RECompiler().compile(pattern), matchFlags); 
    paramString = pattern; 
} 


int callcounterMN = 0; 
protected int matchNodes(int firstNode, int lastNode, int idxStart) 
{ 
    callcounterMN++; 
    if (callcounterMN == 100) { 
     try { 
      String pc1 = new Exception().getStackTrace()[5].getClassName(); 
      if (pc1.indexOf("UpdateWebForm") > 1)  
       System.out.println("regex loop reach "+callcounterMN+" with regex : "+paramString+" "+this.search.substring(0)); 
     } catch (Exception e) {} 
    } 
+0

而不是試圖猜測字符串我會爲每個正則表達式調用設置一個超時,可能會導致CA問題。 –

+0

是的,那是另一種方式。但我仍然想跟蹤這個問題。如果我的正則表達式有問題。 但是,你能給我一些參考設置每個正則表達式的超時?稍後可能會有用。謝謝 – tukimin

+0

請參閱[*取消長時間運行的正則表達式匹配?*](http://stackoverflow.com/questions/910740/cancelling-a-long-running-regex-match) –

回答

1

很久以後,但考慮到目前仍無答案,我會在和球場:谷歌的RE2正則表達式庫旨在防止災難性回溯問題完全,有時以某種程度的性能爲代價:https://github.com/google/re2/wiki/WhyRE2

這不完全是您的問題的答案,因爲這是關於接受任何正則表達式和d確保它永遠不會導致災難性的回溯掛起,而不是檢測那些將使用Apache庫的應用程序,但希望它仍然是對這個問題的一部分訪問者的有用輸入。如果你有能力不支持一些正則表達式模式構造,在某些情況下你可以承受性能問題,你可以承擔測試並交換你正在使用的庫 - 那麼你可能已經解決了這個問題。