4
$\begingroup$

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.

Say

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

Cases[expr,_FunC,All] 

{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

 Cases[expr,_pattern_,All] 

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

$\endgroup$

2 Answers 2

7
$\begingroup$

Maybe something like this:

Cases[expr, _?(StringMatchQ[ToString[Head[#]], "Fun*"] &), All] 
$\endgroup$
3
$\begingroup$
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}

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.