I figured it would be convenient to have a function
that returns a pattern, that match equally nested brackets, of the specified type. Such a pattern is easy to create, but I get some error messages, related to the condition being evaluated prematurely.
The two string-replacements below returns the expected result, but the second one gives the error message
StringCount::strse: String or list of strings expected at position 1 in StringCount[mid,{].
How to make BalancedBracketPattern work?
My idea was that HoldPattern
would prevent the conditional to be evaluated before the actual pattern is used, but that did not work.
Even better, make it only match the stuff inside the brackets!
BalancedBracketPattern[left_: "{", right_: "}"] :=
HoldPattern[
Shortest[left ~~ mid___ ~~ right] /;
StringCount[mid, left] == StringCount[mid, right]];
str = "{{abc}{def}}{blah-blah}";
StringReplace[str,
w : (Shortest["{" ~~ mid___ ~~ "}"] /;
StringCount[mid, "{"] == StringCount[mid, "}"]) :> f[w]]
StringReplace[str, w : BalancedBracketPattern[] :> f[w]]
ClearAll[BalancedBracketPattern]
and then repeating your code. $\endgroup$