-1

I'm looking for a way in VB to find a string between two characters,

"(" and ")".

For example, for the string...

"THIS IS (ONE) AND THIS IS (TWO)"

....I would like for a variable to store the characters between the second set of parenthesis, e.g.

strMyString = "TWO".

But if the string to search only contains one set of parenthesis, to store this instead. e.g.

strFirstString = "THIS IS (ONE)"
strMyString = "ONE"
DJo
  • 2,133
  • 4
  • 30
  • 46
  • 1
    And how have *you* attempted to solve this so far? – Matt Wilko Nov 13 '15 at 10:28
  • So, you want to return the string in the 2nd occurrence of brackets, but if there is no 2nd occurrence then you want to store the 1st. Will there ever be more than 2 occurrences of brackets? If so how do you want to handle this? (It makes a difference to the code) – David Wilson Nov 15 '15 at 14:07

1 Answers1

0

As a preliminary answer, you can use this function to find the string within the last pair or brackets in your test string. If the brackets are in the wrong order or if brackets are missing it will throw an exception.

Private Function StringInLastBracketPair(testString As String) As String
    Dim startBracket, endBracket As Integer
    startBracket = testString.LastIndexOf("(") + 1
    endBracket = testString.LastIndexOf(")")
    If startBracket >= endBracket Or startBracket = 0 Or endBracket = -1 Then
        Throw New System.Exception("String is not formatted properly : " & testString)
    End If
    StringInLastBracketPair = stringToTest.Substring(startBracket, endBracket - startBracket)
End Function
David Wilson
  • 4,369
  • 3
  • 18
  • 31