2017-06-22 112 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