在字符串中查找文本

时间:2018-05-24 13:27:11

标签: .net vb.net

我有一个像这样的字符串:asdf text:a123a)! testing。我想获取此字符串并提取此字符串:a123a)!

我试图这样做:

If TextBox.Text.Trim.ToUpper.Contains("TEXT:") Then
        Dim SearchStringFilter As String = TextBox.Text.Trim
        Dim FilterString As Match = Regex.Match(SearchStringFilter, "text:([A-Za-z0-9\-])", RegexOptions.IgnoreCase)
        If FilterString .Success Then
            Dim SubFilterString As String = StateFilterString.Value.ToUpper.Replace("TEST:", "")
            MessageBox.Show(SubFilterString)
        End If
    End If

但是,此代码似乎无法正常工作。它只输出" 1"。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:3)

您可以使用IndexOf来获取所需的部分。

    Dim str As String = "asdf text:a123a)! testing"
    Dim index1 As Integer = str.IndexOf("text:") + "text:".Length
    Dim index2 As Integer = str.IndexOf(" ", index1)
    Dim result As String = str.Substring(index1, index2 - index1)

您需要添加错误检查。

如果没有空间,你可以把所有东西都拿到最后。

    If index2 = -1 then
        result = str.Substring(index1)
    Else
        result = str.Substring(index1, index2 - index1)
    End If

答案 1 :(得分:0)

你可以使用拆分: - Dim Subject as string =“asdf text:a123a)!testing” “ Dim DivArr As Char()= {“:”c,“”c} '使用“:”和“”作为分隔符分割成段 - 得到第3个元素 Dim part3 As String = Subject.Split(DivArr)(2) 或一行 Dim part3 As String = Subject.Split({“:”c,“”c})(2)

答案 2 :(得分:0)

Regex.Split允许您在保留文本原始大小写的同时不区分大小写。非常方便。

Sub Ding()
    Dim firstItem As Boolean = True
    For Each s As String In Regex.Split(TextBox1.Text, "text:", RegexOptions.IgnoreCase) ' <-- this is the magic
        If firstItem Then
            firstItem = False 'the first item didn't have 'text:', so ignore it
        Else
            If s.Contains(" ") Then
                s = s.Split(" ").First
            End If
            MsgBox(s)
        End If
    Next
End Sub
相关问题