get string between other string vb.net

2019-02-24 00:44发布

问题:

I have code below. How do I get strings inside brackets? Thank you.

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

回答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

This should do it.

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

Would also work.



回答2:

This is what regular expressions are for. Learn them, love them:

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

Two lines of code instead of more than 10.

In the words of Stephan Lavavej: “Even intricate regular expressions are easier to understand and modify than equivalent code.”



回答3:

  1. Use String.IndexOf to get the position of the first opening bracket (x).

  2. Use IndexOf again the get the position of the first closing bracket (y).

  3. Use String.Substring to get the text based on the positions from x and y.

  4. Remove beginning of string up to y+1.

  5. Loop as required

That should get you going.



回答4:

This may also work:

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

Also 2 lines.