让其他字符串vb.net之间串(get string between other string vb

2019-06-26 14:06发布

我有下面的代码。 我如何获得括号内的字符串? 谢谢。

Dim tmpStr() As String
    Dim strSplit() As String
    Dim strReal As String
    Dim i As Integer

    strWord = "hello (string1) there how (string2) are you?"

    strSplit = Split(strWord, "(")
    strReal = strSplit(LBound(strSplit))

    For i = 1 To UBound(strSplit)
        tmpStr = Split(strSplit(i), ")")
        strReal = strReal & tmpStr(UBound(tmpStr))
    Next

Answer 1:

Dim src As String = "hello (string1) there how (string2) are you?"
Dim strs As New List(Of String)

Dim start As Integer = 0
Dim [end] As Integer = 0

While start < src.Length

    start = src.IndexOf("("c, start)
    If start <> -1 Then
        [end] = src.IndexOf(")"c, start)
        If [end] <> -1 Then
            Dim subStr As String = src.Substring(start + 1, [end] - start - 1)
            If Not subStr.StartsWith("(") Then strs.Add(src.Substring(start + 1, [end] - start - 1))
        End If
    Else
        Exit While
    End If

    start += 1 ' Increment start to skip to next (

End While

这应该这样做。

Dim result = Regex.Matches(src, "\(([^()]*)\)").Cast(Of Match)().Select(Function(x) x.Groups(1))

也将工作。



Answer 2:

这是正则表达式是。 了解他们,爱他们:

' Imports System.Text.RegularExpressions
Dim matches = Regex.Matches(input, "\(([^)]*)\)").Cast(of Match)()
Dim result = matches.Select(Function (x) x.Groups(1))

两行的代码,而不是超过10。

在斯蒂芬Lavavej的话:“即使是复杂的正则表达式更容易理解和比同等代码的修改。”



Answer 3:

  1. 使用String.IndexOf拿到第一开口支架(X)的位置。

  2. 使用的IndexOf再次拿到第一闭合支架(Y)的位置。

  3. 使用String.Substring获得基于来自xy位置的文本。

  4. 删除字符串年初增长到y +1。

  5. 循环所需

这应该让你去。



Answer 4:

这也可能工作:

Dim myString As String = "Hello (FooBar) World"
Dim finalString As String = myString.Substring(myString.IndexOf("("), (myString.LastIndexOf(")") - myString.IndexOf("(")) + 1)

另外2行。



文章来源: get string between other string vb.net