2017-06-22 55 views
1

我代表對象屬性的字符串:Visual Basic中:從字符串解析數與正則表達式

Dim path = "Person.AddressHistory(0).Street1" 

,我使用path.Split("."C)分裂它。然後我使用For-Each循環遍歷它。我想檢查是否有任何「路徑部分」(或屬性名稱),如AddressHistory(0)包含圓括號和索引值,那麼我希望提取索引值(在本例中爲整數0)。

然後,我將最終能夠使用此技術來查找最後路徑部分(即Street1(或給定路徑指向的任何值))的值。

雖然我不太瞭解visual basic的正則表達式或字符串解析。到目前爲止,我有這樣的:

Private Function GetValue(root As Object, path As String) As Object 

    Dim pathSections = path.Split("."C) 

    For Each section In pathSections 

     Dim index As Integer 
     Dim info As System.Reflection.PropertyInfo 

     If section.Contains("(%d)") Then 
      'todo: get index... 
      'index = section.<Get index using regex>() 
     End If 

     ' reflection to get next property value 
     ' root = <get next value...> 
    Next 

    Return root 

End Function 

回答

1

只匹配單詞組成的字符裏面(...) 1+數字在最後一節中,你可以使用

^\w+\(([0-9]+)\)$ 

regex demo。然後獲得match.Groups(1).Value

如果沒有匹配,字符串末尾的圓括號內沒有數字。

參見一個demo of this approach

Dim path As String = "Person.AddressHistory(0).Street1" 
Dim rx As Regex = New Regex("^\w+\(([0-9]+)\)$") 
Dim pathSections() As String = path.Split("."c) 
Dim section As String 
For Each section In pathSections 
    Dim my_result As Match = rx.Match(section) 
    If my_result.Success Then 
     Console.WriteLine("{0} contains '{1}'", section, my_result.Groups(1).Value) 
    Else 
     Console.WriteLine("{0} does not contain (digits) at the end", section) 
    End If 
Next 

結果:

Person does not contain (digits) at the end 
AddressHistory(0) contains '0' 
Street1 does not contain (digits) at the end 

注意捕獲組編號從1開始作爲第0組是整個匹配。這意味着match.Groups(0).Value = match.Value。所以,在這種情況下,AddressHistory(0)match.Groups(0).Value0match.Groups(1).Value

+0

謝謝。我切換到使用'Regex.Match(section,「^ \ w + \(([0-9] +)\)$」)'檢索一個Match對象。 'match.Groups(1).Value'的組索引是否從0或1開始?這讓我感到困惑。 – Mayron

+0

@Mayron我添加了一個演示和捕獲組編號的一些解釋。 –

+0

非常感謝!我正在使用Regex類的共享函數「Match」,而不是創建一個實例。不知道這是否會有所作爲,但無論哪種方式,我都會使用您的示例,因爲它完美地工作。 – Mayron