Visual Basic:使用Regex从String中解析数字

时间:2017-06-22 10:21:14

标签: regex string vb.net parsing

我有一个表示对象属性的字符串:

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 个答案:

答案 0 :(得分: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