Ok, I give up. I can't figure how to tell Mathematica to do replacement using a pattern except for some special case. Easier to explain with small example.

I want to change pattern Exp[any_. c] to c for all cases of pattern any except when any happened to be contain the literal symbol x anywhere in it.

So Exp[5 c] will be replaced to c and so will Exp[y c] but for Exp[x c] or Exp[Sin[x] c] I want no replacement to happen since the term multiplying c has x in it.

I am trying to use Except but can't get it to work. This is what I tried

This does not work

Exp[ x c] /. Exp[any_. c]:> c

So I need a way to set a pattern which says anything except x. So tried

Exp[ x  c] /.  Exp[Alternatives[Except[x], any1_.]  c] :> c

Mathematica graphics

It changed it to c, so pattern matched.

Do I need to use Verbatim in pattern for this? How?

I reached my limit in pattern matching skills in Mathematica so I need help :)

  • 4
    $\begingroup$ Maybe Exp[any_. c] /; FreeQ[any, x] :> c $\endgroup$
    – Coolwater
    Commented Jul 21, 2017 at 8:30
  • $\begingroup$ @Coolwater nice! It seems to work. Will test it more. Thanks. I was wondering how Except[] can be used there. I saw Except[] used in Cases but not in Replace in the help pages. $\endgroup$
    – Nasser
    Commented Jul 21, 2017 at 8:39
  • 2
    $\begingroup$ Since you want to test for the presence of x anywhere in the prefactor to c, I don't thing Except is going to be of much use here. I can't think of a pattern that would match any expression that contains an x somewhere without using FreeQ or MemberQ as conditions. The problem here is that you're trying to find x at any level of the expression, so you'll have to use FreeQ or MemberQ in some way. $\endgroup$ Commented Jul 21, 2017 at 10:35

1 Answer 1


Here is a tweak of @Coolwater's answer in his comments:

    {Exp[c], Exp[5 c], Exp[y c], Exp[x c], Exp[Sin[x] c]},
    Exp[Optional[_?(FreeQ[x])] c] :> c

{c, c, c, E^(c x), E^(c Sin[x])}


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.