Matching brackets in a string

后端 未结 9 1643
小蘑菇
小蘑菇 2020-12-03 03:47

What is the most efficient or elegant method for matching brackets in a string such as:

\"f @ g[h[[i[[j[2], k[[1, m[[1, n[2]]]]]]]]]] // z\"
<
9条回答
  •  被撕碎了的回忆
    2020-12-03 04:15

    Ok, here is another answer, a bit shorter:

    Clear[replaceDoubleBrackets];
    replaceDoubleBrackets[str_String, openSym_String, closeSym_String] := 
    Module[{n = 0},
      Apply[StringJoin, 
       Characters[str] /. {"[" :> {"[", ++n}, 
         "]" :> {"]", n--}} //. {left___, {"[", m_}, {"[", mp1_}, 
          middle___, {"]", mp1_}, {"]", m_}, right___} /; 
           mp1 == m + 1 :> {left, openSym, middle, 
            closeSym, right} /. {br : "[" | "]", _Integer} :> br]]
    

    Example:

    In[100]:= replaceDoubleBrackets["f[g[h[[i[[j[2], k[[1, m[[1, n[2]]]]]]]]]]]", "(", ")"]
    
    Out[100]= "f[g[h(i(j[2], k(1, m(1, n[2]))))]]"
    

    EDIT

    You can also use Mathematica built-in facilities, if you want to replace double brackets specifically with the symbols you indicated:

    Clear[replaceDoubleBracketsAlt];
    replaceDoubleBracketsAlt[str_String] :=
      StringJoin @@ Cases[ToBoxes@ToExpression[str, InputForm, HoldForm],
         _String, Infinity]
    
    In[117]:= replaceDoubleBracketsAlt["f[g[h[[i[[j[2], k[[1, m[[1, n[2]]]]]]]]]]]"]
    
    Out[117]= f[g[h[[i[[j[2],k[[1,m[[1,n[2]]]]]]]]]]]
    

    The result would not show here properly, but it is a Unicode string with the symbols you requested.

提交回复
热议问题