6
$\begingroup$

I have an expression of the form

expr = 3*(a.b)*(c.d)*f[x] + 5*(m.n)*(p.q)*(r.s)*f[y]

and want to extract all possible subexpressions matching the pattern ((_).(_))*f[_]. Expected result (in arbitrary order) is:

{(a.b)*f[x], (c.d)*f[x], (m.n)*f[y], (p.q)*f[y], (r.s)*f[y]}

Built-in function Cases seem to ignore Flat Attribute of Times and gives nothing:

Cases[expr, ((_).(_))*f[_], Infinity]

{}

How can I get all possible subexpressions matching the pattern ((_).(_))*f[_]?

$\endgroup$

2 Answers 2

7
$\begingroup$

To get all the different ways this pattern can match, we can use ReplaceList, since none of Cases, Replace, ReplaceAll tries to match the same part more than once. Here is one way:

ReplaceList[expr, 
 d_. + Times[c___, Dot[a_, b_], f[x_]] :> Dot[a, b] f[x]]

{a.b f[x], c.d f[x], m.n f[y], p.q f[y], r.s f[y]}

The reason I'm writing Dot[a_, b_] and not just a_.b_ is that looking at the FullForm of what I'm trying to match always seems to help me figure out a good pattern to use :)

$\endgroup$
6
$\begingroup$

You can also use SequenceCases with the option Overlaps -> All:

SequenceCases[List @@ expr, { _.  a_Dot  b_f} :> a b, Overlaps -> All]
 {c.d f[x], a.b f[x], r.s f[y], p.q f[y], m.n f[y]}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.