Johns Yong Johns Yong - 8 months ago 21 Question

Detect the closing bracket belong to the open bracket when there is more than one open & close bracket inside the bracket

Actually, I want to do this to detect the value inside the rounding bracket and do the rounding to whatever inside the rounding bracket. For example:

Dim h As String = "ROUNDING(30.98998(10))*2+3"
Dim r As String = h.ToString.Substring(h.ToString.IndexOf("ROUNDING(") + 1, h.ToString.IndexOf(")") - 1 - h.ToString.IndexOf("ROUNDING("))

In this case, after the
there is one more
. How to make the open bracket on the
to match to the end of it's closing bracket?

Thanks in advance!

Ian Ian

You could use the following ReadInBetweenSameDepth Function.

Public Function ReadInBetweenSameDepth(str As String, delimiterStart As Char, delimiterEnd As Char) As String
    If delimiterStart = delimiterEnd OrElse String.IsNullOrWhiteSpace(str) OrElse str.Length <= 2 Then
        Return Nothing
    End If
    Dim delimiterStartFound As Integer = 0
    Dim delimiterEndFound As Integer = 0
    Dim posStart As Integer = -1
    For i As Integer = 0 To str.Length - 1
        If str(i) = delimiterStart Then
            If i >= str.Length - 2 Then
                'delimiter start is found in any of the last two characters
                Return Nothing
            End If
            'it means, there isn't anything in between the two
            If delimiterStartFound = 0 Then
                'first time
                posStart = i + 1
            End If
            'assign the starting position only the first time...
                'increase the number of delimiter start count to get the same depth
            delimiterStartFound += 1
        End If
        If str(i) = delimiterEnd Then
            delimiterEndFound += 1
            If delimiterStartFound = delimiterEndFound AndAlso i - posStart > 0 Then
                Return str.Substring(posStart, i - posStart)
                'only successful if both delimiters are found in the same depth
            End If
        End If
    Return Nothing
End Function

It basically checks if the delimiters (such as ( and ) ) are in the same "depth".