vb.net从字符串中获取某些字符

时间:2015-10-30 19:14:21

标签: vb.net

我有在vb.net中使用的字符串,我希望能够获得字符串的某些部分。

一个例子是:

1 x示例项目1

从此我想得到1Example Item 1

然后可能有一个项目:

10 x示例2

所以我希望获得10Example 2

我想过使用像substring这样的东西:

Dim substring As String = Substring(0, 3)

但这根本不会起作用,具体取决于物品的数量(如果它的长度为1/2或3位)

还有一些字符串只是Example Item 10,而开头没有1 x10 x,我怎样才能看到它是以1/10 x开头还是不?

2 个答案:

答案 0 :(得分:2)

使用此代码:

Dim subject = "1 x Example 2"
Dim leftPart, rightPart As String
If Regex.IsMatch(subject, "\d+\sx\s") Then
    Dim splitText As String() = subject.Split({" x "}, StringSplitOptions.None)
    leftPart = splitText(0)
    rightPart = splitText(1)
Else
    'Treat it as you wish.
End If

答案 1 :(得分:-1)

    Dim substring As String = "10 x Example 2"
    Dim myStrings() As String

    myStrings = MyStringParser(substring)
    substring = "Example 4"
    myStrings = MyStringParser(substring)
    substring = " x Example 4"
    myStrings = MyStringParser(substring)

Public Function MyStringParser(value As String) As String()

    Dim returnValue() As String = {"", ""}

    If value.Length > 0 Then
        If value.Contains(" x ") Then
            returnValue = value.Replace(" x ", "|").Split("|"c)
        Else
            returnValue(1) = value
        End If
    Else
        returnValue(1) = value
    End If

    Return returnValue

End Function