Johns Yong - 2 years ago 61
Vb.net 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
`ROUNDING(`
there is one more
`(`
and
`)`
. How to make the open bracket on the
`ROUNDING`
to match to the end of it's closing bracket?

Thanks in advance!

Answer Source

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
Next
Return Nothing
End Function
``````

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download