需要帮助在VB中分割字符串

时间:2016-06-02 09:01:33

标签: vb.net string

我有一个服务器返回的字符串,我需要从中获取一些信息。这是字符串:

(stock-info(msg-id 57)(回复4)(参考" IC00000000234" std)(总计(方框61))(有效(方框61)))

我需要获取框的总数和有效框,并将它们放入参数中。我已经尝试使用子串并将字符串分成不同的部分,问题是这个字符串可能是不同的长度所以它总是带回正确的结果。任何帮助将不胜感激。

由于

4 个答案:

答案 0 :(得分:2)

这是正则表达式有用的问题:

Option Infer On
Option Strict On

Imports System.Text.RegularExpressions

Module Module1

    Sub Main()

        Dim s = "(stock-info (msg-id 57) (reply-to 4) (ref ""IC00000000234"" std) (total (boxes 61)) (valid (boxes 48)) )"

        Dim reTotal As New Regex("total \(boxes ([0-9]+)")
        Dim reValids As New Regex("valid \(boxes ([0-9]+)")

        ' initialise with a value than cannot appear in the string
        ' so it can be checked for later if needed
        Dim totalBoxes As Integer = -1
        Dim validBoxes As Integer = -1

        If reTotal.IsMatch(s) Then
            totalBoxes = CInt(reTotal.Match(s).Groups(1).Value)
        End If

        If reValids.IsMatch(s) Then
            validBoxes = CInt(reValids.Match(s).Groups(1).Value)
        End If

        Console.WriteLine($"Total: {totalBoxes} Valid: {validBoxes}")
        Console.ReadLine()

    End Sub

End Module

输出:

  总计:61有效期:48

答案 1 :(得分:1)

有很多方法可以解决您的问题:

        Dim MyString As String = "(stock-info (msg-id 57) (reply-to 4) (ref ""IC00000000234"" std) (total (boxes 61)) (valid (boxes 61)) )"
    Dim SringExtracted As String = ""
    Dim MyKey As String = ""

    'Total Boxes
    MyKey = "(total (boxes"
    SringExtracted = MyString.Substring(MyString.LastIndexOf(MyKey) + MyKey.Length)
    SringExtracted = Microsoft.VisualBasic.Left(SringExtracted, SringExtracted.IndexOf("))"))
    Dim TotalBoxes As Integer = Val(SringExtracted)

    'Valid Boxes
    MyKey = "valid (boxes"
    SringExtracted = MyString.Substring(MyString.LastIndexOf(MyKey) + MyKey.Length)
    SringExtracted = Microsoft.VisualBasic.Left(SringExtracted, SringExtracted.IndexOf("))"))
    Dim ValidBoxes As Integer = Val(SringExtracted)

答案 2 :(得分:1)

这应该有效。通过“框”拆分字符串,忽略字符串的第一部分,然后在将它们转换回字符串之前删除剩余两个字符串(以字符数组形式)的所有非数字字符。如果你想将它们作为整数,那么就在之后解析它们。

Dim myString = "(stock-info (msg-id 57) (reply-to 4) (ref 'IC00000000234' std) (total (boxes 61)) (valid (boxes 61)) )"

Dim splitArray = myString.Split("boxes ").Skip(1)

Dim totalBoxesAsString = New String(splitArray.First.Where(Function(c) Char.IsDigit(c)).ToArray())
Dim validBoxesAsString = New String(splitArray.Last.Where(Function(c) Char.IsDigit(c)).ToArray())

答案 3 :(得分:1)

您可以在这种情况下使用正则表达式。 https://msdn.microsoft.com/en-us/library/hs600312(v=vs.110).aspx

Imports System.Text.RegularExpressions

Dim input As String = "(stock-info (msg-id 57) (reply-to 4) (ref ""IC00000000234"" std) (total (boxes 60)) (valid (boxes 61)) )"
For Each match As Match In Regex.Matches(input, "\(total \(boxes (\d+)\).+\(valid \(boxes (\d+)\)")
    Console.WriteLine("Total={0}, Valid={1}", match.Groups.Item(1).Value, match.Groups.Item(2).Value)
Next