【问题标题】:VB.NET: Searching for certain values in textVB.NET:在文本中搜索某些值
【发布时间】:2016-08-30 23:00:43
【问题描述】:

我编写了一段代码,它读取一个字符串并尝试从中获取某些部分。

特别是,我想获取包含在自定义文本书写标签中的数字:[propertyid=]。例如[propertyid=541] 需要返回给我541

这种搜索和检索发生在文本中,并且需要与文本中的标签数量一样频繁。

我已经写出了有效的代码

Module Module1

    Sub Main()
        Dim properties As New List(Of String)
       'context of string doesn't matter, only the ids are important
        Dim text As String = "Dit is de voorbeeld string. Eerst komt er gewoon tekst. Daarna een property als [propertyid=1155641] met nog wat tekst. Dan volgt nog een [propertyid=1596971418413399] en dan volgt het einde."
        Dim found As Integer = 1

        Do
            found = InStr(found, text, "[propertyid=")
            If found <> 0 Then
                properties.Add(text.Substring(found + 11, text.IndexOf("]", found + 11) - found - 11).Trim())
                found = text.IndexOf("]", found + 11)
            End If
        Loop While found <> 0




        Console.WriteLine("lijst")
        For Each itemos As String In properties
            Console.WriteLine(itemos)
        Next
    End Sub

End Module

但我不禁觉得这不是最佳选择。我很确定这可以更容易地编写或借助SubstringIndexOf 以外的其他工具来编写。尤其是这样,因为我需要对索引和循环进行一些操作。

对改进这段代码有什么建议吗?

【问题讨论】:

    标签: regex vb.net string parsing


    【解决方案1】:

    您可以使用regular expressions 来完成此类任务。

    在这种情况下,匹配[propertyid=NNNN] 的模式是:

    \[propertyid=(\d+)\]

    在捕获组(括号)中隔离一组一个或多个数字 - \d+,以便匹配引擎检索。

    这是一个代码示例:

    Imports System.Text.RegularExpressions
    
    Module Module1
    
        Sub Main()
    
            Dim properties As New List(Of String)
            'context of string doesn't matter, only the ids are important
            Dim text As String = "Dit is de voorbeeld string. Eerst komt er gewoon tekst. Daarna een property als [propertyid=1155641] met nog wat tekst. Dan volgt nog een [propertyid=1596971418413399] en dan volgt het einde."
            Dim pattern As String = "\[propertyid=(\d+)\]"
    
            For Each m As Match In Regex.Matches(text, pattern)
                properties.Add(m.Groups(1).Value)
            Next
    
            For Each s As String In properties
                Console.WriteLine(s)
            Next
    
            Console.ReadKey()
    
    
        End Sub
    
    End Module
    

    【讨论】:

    • 谢谢!我想我忘记了这些存在。
    • 不用担心。希望它有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2013-12-18
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多