I want to find a function (could be user-defined) from an expression based on pattern matching. However, I do not know the exact name (Head) of the function but know only the first few characters.


expr= 2 x + x^2 FunC[1,x] + x^3 FunC[2,x];

Now if I knew the full name of the function (in this case FunC), then I could do something like


{FunC[1, x], FunC[2, x]}

to access the occurrence of FunC.

However, say I do not know the full name/Head of the pattern, I know that it starts with Fun (or ends with unC). In that case, how do I access the occurrence of FunC in the expression using part of the Head?

Something like


where _pattern_ could be part of the actual name/Head like Fun, unC.


2 Answers 2


Maybe something like this:

Cases[expr, _?(StringMatchQ[ToString[Head[#]], "Fun*"] &), All]
expr = 2 x + x^2 MyFun1[1, x] + x^3 MyFun2[2, x];

p = Position[expr, x_ /; StringMatchQ[ToString[x], "My*"], {}, Heads -> False]

{{2, 2}, {3, 2}}

Extract[expr, p]

{MyFun1[1, x], MyFun2[2, x]}

q = Position[expr, x_ /; StringMatchQ[ToString[x], "My*"], {-1}]

{{2, 2, 0}, {3, 2, 0}}

Extract[expr, q]

{MyFun1, MyFun2}


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.