tdjfdjdj
tdjfdjdj

Reputation: 2471

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}","}")

Upvotes: 1

Views: 1859

Answers (2)

Jay Shah
Jay Shah

Reputation: 21

//Method 
String extractStringBetweenSymbols(String input,
String startsymbol,
String endsymbol){
  int startIndex=input.indexOf(startsymbol);
int endIndex=input.indexOf(endsymbol,
  startIndex+startSymbol.length);
if(startIndex != -1 && endIndex != -1){
    return input.substring(startIndex+startSymbol.length,
    endIndex);
  }
return'';
}

//Usage 
String heading="Hello {WORLD} , Good morning";
String startSymbol"{";
String endSymbol="}";
String extractedString=extractStringBetweenSymbols(heading,
startsymbol,
endsymbol);
print("=======> $extractedString");

// Output: =======> WORLD

THIS IS HELPFUL FOR DART.

Upvotes: 2

Eder
Eder

Reputation: 1884

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

Upvotes: 4

Related Questions