2016-12-25 106 views
1

我正在研究D代碼中一個非常依賴性能的部分。爲此,我希望將一個關聯數組映射到一個Regex,以便稍後使用它。正則表達式作爲關聯數組的關鍵?

當我試圖做到這一點,它給了我錯誤,index is not a type or expression。我怎樣才能使用這個正則表達式作爲我的數組鍵?

編輯:對於代碼,這裏就是我想在我的類定義:

View[Regex] m_routes; 

我想要的,這樣我可以添加像下面的路線:

void add(string route, View view) 
{ 
    auto regex = regex(route.key, [ 'g', 'i' ]); 

    if (regex in m_routes) 
     throw new Exception(format(`Route with path, "%s", is already assigned!`, route)); 

    m_routes[regex] = view; 
} 

這然後讓我檢查一條路線上的正則表達式,而不必重新構建每條路線,如下所示:

View check(string resource) 
{ 
    foreach (route; m_routes.byKeyValue()) 
    { 
     auto match = matchAll(resource, route.key); 

     // If this regex is a match 
     // return the view 
     if (!match.empty) 
     { 
      return route.value; 
     } 
    } 

    return null; 
} 

任何幫助將不勝感激,謝謝!

+0

這將是更容易幫助你,如果你提供顯示問題的一些示例代碼。 –

+0

@JonathanMDavis爲我試圖實現的目標添加了一些代碼 – Tinfoilboy

回答

5

看來std.regex.Regex是一個別名,需要一個類型參數:

(從std.regex.package,在釋放2.071.0線289)

public alias Regex(Char) = std.regex.internal.ir.Regex!(Char); 

換句話說,你需要指定正則表達式的字符類型。對於string,那會是char

View[Regex!char] m_routes; 
+0

非常感謝,這個固定了! 接受爲答案。 – Tinfoilboy