VB.NET:如何在一行中的特定单词之后找到一个单词并存储它

时间:2013-02-26 11:37:13

标签: vb.net

我有一连串的话从机器到我系统的超级终端,我正在使用USB转串口线。我想找到一些在该字符串中的特定单词后面然后存储它的值。

我使用线程和拆分概念来执行此操作,但根据计算机的要求和操作,它将无法在运行时正常工作。

我想要捕获的值来自特定的单词。我想跳过那些单词并只存储值。怎么做?

我在下面给出了该字符串的示例:

MEAN 49  50
SD   500 10
MIN  100 5
MAX  50  45.56

在此我只想存储值,例如4950,然后放弃MEAN。然后放弃SD并存储50010,依此类推。

2 个答案:

答案 0 :(得分:1)

您可以使用StreamReader对象一次读取一行流。然后,您可以使用String.Split方法轻松解析该行。我建议创建一个或多个表示正在读取的数据的类,如下所示:

Public Class LineData
    Public Property Label As String
    Public Property Value1 As Decimal
    Public Property Value2 As Decimal
End Class

Public Function ReadNextLine(stream As Stream) As LineData
    Dim reader As New StreamReader(stream)
    Dim line As String = reader.ReadLine()
    Dim data As LineData = Nothing
    If line IsNot Nothing Then
        Dim words() As String = line.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
        If words.Length = 3 Then
            data = New LineData()
            data.Label = words(0)
            data.Value1 = Decimal.Parse(words(1))
            data.Value2 = Decimal.Parse(words(2))
        End If
    End If
    Return Data
End Function

注意,这是一个基于您提供的示例数据的非常简单的示例。如果不同的行具有不同数量的数字参数,那将进一步使逻辑复杂化。在我的示例中,如果无法读取数据,则该方法返回Nothing。此外,如果行中的最后两个单词不是数字,则该方法将抛出异常。因此,您需要将其包装在一些额外的异常处理中。

答案 1 :(得分:0)

这可能是您正在寻找的。虽然我个人创建了一个存储类型(平均值,中位数等),firstvalue和secondvalue的类。

通过它的声音,你想要它做的就是将值转储到某种存储中,因此这就足够了。

Dim Values as New List(Of Decimal)

'Use a streamreader to read each line of text
Using reader As StreamReader = New StreamReader(*your text source*)
'Read the line 
Dim linetext as string = reader.ReadLine
Dim myValue as decimal
'Split the line
Dim splitText() = linetext.Split(" ")
'Analyze each section of the line, if its possible to parse the value as a decimal then add it to the list of values to be stored.
For Each txt in splitText
If Decimal.TryParse(txt, myValue) then Values.Add(myValue)
Next
End Using