2016-08-30 4 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]にマッチするパターンがある:

1桁以上の数字の組分離

\[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

心配はいりません。それが助けてくれたらと思います。 –

関連する問題