Extracting an expression matching a pattern from a large expression

后端 未结 3 644
臣服心动
臣服心动 2021-02-04 12:44

I have a Mathematica expression that contains a single square root, schematically

expr = a / (b + Sqrt[c]);

where a,b

相关标签:
3条回答
  • 2021-02-04 13:13

    If you are willing to change the assignment to expr, you can do this:

    expr = Hold[a / (b + Sqrt[c])];
    
    Cases[expr, HoldPattern @ Sqrt[x_] :> x, Infinity]
    

    The Hold in the assignment statement prevents Mathematica from applying any simplifications to the expression. In this case, Sqrt[c] gets "simplified" into Power[c,Rational[1,2]].

    The HoldPattern is essential in the Cases expression to prevent the same simplification from happening to the pattern being matched.

    0 讨论(0)
  • 2021-02-04 13:19

    Theoretically, this should work correctly:

    extractSqrt = Cases[ToBoxes@#, SqrtBox@x_ :> ToExpression@x, Infinity] &;
    
    extractSqrt[expr]
    
    0 讨论(0)
  • 2021-02-04 13:23

    I await a few examples, but in the meantime, try:

    Cases[expr, x_^(1/2 | -1/2) :> x, Infinity]
    

    The standard internal form for Sqrt(x) is Power[x, 1/2].

    0 讨论(0)
提交回复
热议问题