Get a string between another vb.net string

I have the code below. How to get strings in brackets? Thanks.

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 
+4
source share
4 answers
 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 

That should do it.

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

Will also work.

+2
source

This is what for regular expressions . 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.

According to Stefan Lavavey: "Even complex regular expressions are easier to understand and change than equivalent code."

+3
source
  • Use String.IndexOf to get the position of the first open bracket (x).

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

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

  • Delete the beginning of the line to y + 1.

  • Loop as needed

That should make you.

+1
source

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 two lines.

0
source

All Articles