2016-08-30 78 views
1

我編寫了一段代碼,它讀取一個字符串並嘗試從中獲取某些部分。VB.NET:在文本中搜索某些值

特別是,我想要得到包含在自定義文本書寫標記中的數字:[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之外的其他工具更容易寫出。特別是如此,因爲我需要玩一些索引和循環。

有關改進這段代碼的任何建議?

回答

4

您可以使用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 
+0

THX!猜猜我忘了這些存在。 – Whitekang

+0

不用擔心。希望它有幫助。 –