2014-02-07 41 views
2

有沒有辦法將Regex用作Dictionary中的關鍵字?像Dictionary(Of Regex, String)正則表達式作爲VB.NET字典中的關鍵字

我試圖在列表中找到一個Regex(假設第一次沒有字典),它與字符串匹配。

我可以通過手動迭代RegEx表達式列表來完成。我只是在尋找一種更簡單的方法,例如DictionaryTryGetValue

+1

您是否嘗試過? –

+0

也許你想要的是正相反,鍵爲字符串,值爲正則表達式。這聽起來更有用。 –

+0

你需要平等的模式和選項等?我不知道正則表達式是否優先於等於。 –

回答

2

當您使用Regex作爲Dictionary中密鑰的類型時,它將起作用,但它會按對象實例比較鍵,而不是通過表達式字符串。換句話說,如果您創建兩個單獨的Regex對象,並使用相同的表達式,然後將它們添加到字典中,則它們將被視爲兩個不同的鍵(因爲它們是兩個不同的對象)。

Dim d As New Dictionary(Of Regex, String)() 
Dim r As New Regex(".*") 
Dim r2 As New Regex(".*") 
d(r) = "1" 
d(r2) = "2" 
d(r) = "overwrite 1" 
Console.WriteLine(d.Count) ' Outputs "2" 

如果要使用表達式爲重點,而不是Regex對象,那麼你需要創建你的字典用String一鍵式,如:

Dim d As New Dictionary(Of String, String)() 
d(".*") = "1" 
d(".*") = "2" 
d(".*") = "3" 
Console.WriteLine(d.Count) ' Outputs "1" 

然後,當您使用表達式字符串作爲鍵時,可以使用TryGetValue,如您所述:

Dim d As New Dictionary(Of String, String)() 
d(".*") = "1" 
Dim value As String = Nothing 

' Outputs "1" 
If d.TryGetValue(".*", value) Then 
    Console.WriteLine(value) 
Else 
    Console.WriteLine("Not found") 
End If 

' Outputs "Not found" 
If d.TryGetValue(".+", value) Then 
    Console.WriteLine(value) 
Else 
    Console.WriteLine("Not found") 
End If