Assuming I have a string such as:
abc(def(gh)il(mn(01))afg)lmno(sdfg*)
How can I determine the matching bracket for the first one? (meaning (def(gh)il(mn(01))afg))
I have tried to create a between function by counting the number of open brackets until the first ‘)’, but it doesn’t work on strings like this one.
You could use a function that simply traverses the string while keeping track of a stack of indices of opening parentheses. Whenever you encounter a closing parenthesis, you know that it matches with the index at the top of the stack.
For example:
This function returns a list of all pairs of indices belonging to pairs of matching parentheses.
Applying the function to your example string gives:
The opening parenthesis you were interested in appears at index 3. The returned list shows that the matching closing parenthesis is to be found at index 24.
The following functions gives you all properly parenthesised segments of a string:
For example:
Following Frerich Raabe’s suggestion, we can now also write a function that only returns the leftmost segment:
For example:
Note that
firstParenSegwill fail if the input string does not contain at least one pair of matching parentheses.Finally, a small adaption of the
parenPairsfunction lets it fail on unbalanced parentheses: