get string between other string vb.net

前端 未结 4 1726
小鲜肉
小鲜肉 2021-01-19 15:32

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 A         


        
相关标签:
4条回答
  • 2021-01-19 16:11

    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.”

    0 讨论(0)
  • 2021-01-19 16:14
    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.

    0 讨论(0)
  • 2021-01-19 16:22
    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.

    0 讨论(0)
  • 2021-01-19 16:26

    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.

    0 讨论(0)
提交回复
热议问题