# How can I extract something from an expression and assign it without changing the expression?

I am researching how to extract a certain value from an expression by using a pattern mechanism without actually changing the original expression.

The paragraph above could be very ambiguous, so here is an example. The aim here is to extract the number 4 before t and assign it to Symbol j.

Clear["Global*"];

n = 3 Cos[4 t + 2]
(* 3 Cos[2 + 4 t] *)

n = 3 Cos[4 t + 2] /. _ Cos[r_ t + _] :> (k = r)
(* 4 *)
k
(* 4 *)
n
(* 4 *)


But unfortunately, it assigns 4 to n as well. Even if I use ; after k = r, it assigns Null to n as you can see below.

Clear["Global*"]

n = 3 Cos[4 t + 2]
(* 3 Cos[2 + 4 t] *)
n = 3 Cos[4 t + 2] /. _ Cos[r_ t + _] :> (k = r;)
k
(* 4 *)
n


How to extract 4 and assign it to k without having the original expression changed?

Parenthesize:

In:= (n = 3 Cos[4 t + 2]) /. _ Cos[r_ t + _] :> (k = r);

In:= {n, k}

Out= {3 Cos[2 + 4 t], 4}


Equivalently, use full form:

In:= n =.; k =.

In:= ReplaceAll[n = 3 Cos[4 t + 2], _ Cos[r_ t + _] :> (k = r)];

In:= {n, k}

Out= {3 Cos[2 + 4 t], 4}

• Thank you for the answer! There was a very simple solution here. Surprising! – Smart Humanism Dec 30 '15 at 19:43

The construction is a little funny, but you could also use Cases:

Clear[n, k, t]
k = First@Cases[n = 3 Cos[4 t + 2], Cos[r_ t + _] :> r, Infinity]
n
(* {4} *)
(* 3 Cos[4 t + 2] *)


I very much like replacement rules with side effects, but I think here it is a little strange. The nice thing about using Cases here is that you can strip off the First, and then k will be set to the list of matches (which would work for the more general case of there being more than one match).

• Thank you for the answer! I also thought about this but I wanted to approach in a simpler way. – Smart Humanism Dec 30 '15 at 19:45