Search code examples
stringms-accessvbaloops

get value between two characts in string


I need a value between two characters in a string.The values are between { and }. Sometimes there may be more then 1 occurrence.

  var = split("this {is}  a {test}","{")
 var = split("this {is}  a {test}","}")

Solution

  • I don't believe that splitting the string would be a solution since you need to know the position of the character that is splitting your string.

    So I'm giving you two solutions

    Solution #1

    Regular Expression

    First of all, you'll need to add the reference to VBA Regular Expression. Tool -> References & Microsoft VBScript Regular Expression 5.5

    Code

    Sub Test1()
        Dim sText As String
    
        Dim oRegExp As RegExp
        Dim oMatches As MatchCollection
    
        sText = "this {is}  a {test}"
    
        Set oRegExp = New RegExp
    
        With oRegExp
            oRegExp.IgnoreCase = True
            oRegExp.Pattern = "{([^\}]+)"
            oRegExp.Global = True
        End With
    
        Set oMatches = oRegExp.Execute(sText)
    
        For Each Text In oMatches
            Debug.Print Mid(Text, 2, Len(Text))
        Next
    End Sub
    

    Solution #2

    Linear Search

    Code

    Sub Test2()
        Dim bIsBetween As Boolean
    
        Dim iLength As Integer
    
        Dim sText As String
        Dim sToken As String
    
        bIsBetween = False
    
        sToken = ""
        sText = "this {is}  a {test}"
    
        iLength = Len(sText) - 1
    
        For I = 1 To iLength
            Dim chr As String
            Dim nextChr As String
    
            chr = Mid(sText, I, 1)
            nextChr = Mid(sText, I + 1, 1)
    
            If (chr = "{") Then
                bIsBetween = True
            End If
    
            If (nextChr = "}") Then
                bIsBetween = False
            End If
    
            If (bIsBetween = True) Then
                sToken = sToken & nextChr
            Else
                If (Len(sToken) > 0) Then
                    Debug.Print sToken
                    sToken = ""
                End If
            End If
        Next I
    End Sub