我代表對象屬性的字符串: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
謝謝。我切換到使用'Regex.Match(section,「^ \ w + \(([0-9] +)\)$」)'檢索一個Match對象。 'match.Groups(1).Value'的組索引是否從0或1開始?這讓我感到困惑。 – Mayron
@Mayron我添加了一個演示和捕獲組編號的一些解釋。 –
非常感謝!我正在使用Regex類的共享函數「Match」,而不是創建一個實例。不知道這是否會有所作爲,但無論哪種方式,我都會使用您的示例,因爲它完美地工作。 – Mayron