我代表对象属性的字符串: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