6
$\begingroup$

I want to pattern match all symbols beginning with $e$

{e1 x e2 y e3 z e4} /. lettersBeginningWithe -> 3

How can this be done in mathematica?

$\endgroup$
2
  • 1
    $\begingroup$ What should happen when e1 = 2; and Hold[{e1 x e2 y e3 z e4}] is the expression you want to search? $\endgroup$
    – Kuba
    Aug 30, 2016 at 6:00
  • 1
    $\begingroup$ This can be useful to match generated symbols such as Unique[]. $\endgroup$
    – QuantumDot
    Aug 30, 2016 at 10:35

3 Answers 3

7
$\begingroup$

You may use SymbolName with StringStartsQ.

{e1 x e2 y e3 z e4} /. s_Symbol /; StringStartsQ["e"]@SymbolName[s] -> 3
(* {81 x y z} *)

Hope this helps.

$\endgroup$
4
$\begingroup$

Improvement Courtesy of Karsten. 7 (see comments)

Just a way using Pick:

var = {e1 , x , e2, y, e3, z, e4};
Pick[var, StringTake[#, 1] & /@ (ToString /@ var), "e"]

Improved:

Pick[var, StringTake[ToString /@ var, 1], "e"]

Using Cases

Cases[var, _?(StringTake[ToString[#], 1] == "e" &)]

Using StringMatchQ (method is corrected by Alexey Popkov, see comments):

Pick[var, StringMatchQ[ToString[#], "e" ~~ ___] & /@ var]

Improved:

Pick[var, StringMatchQ[ToString /@ var, "e" ~~ ___]]
$\endgroup$
6
  • $\begingroup$ Quite excessive use of /@ inside Pick. Unleash the full power and beauty of Pick by taking advantage of the Listable attribute: Pick[var, StringTake[ToString /@ var, 1], "e"] and Pick[var, StringContainsQ[ToString /@ var, "e" ~~ _]]. $\endgroup$
    – Karsten7
    Aug 30, 2016 at 6:34
  • $\begingroup$ @Karsten7. my bad habits die hard...and I have been too slow to recognize and apply the operator forms. :) $\endgroup$
    – ubpdqn
    Aug 30, 2016 at 6:38
  • $\begingroup$ Note that StringContainsQ["aer", "e" ~~ _] returns True what isn't what you want. The correct test is StringMatchQ["aer", "e" ~~ ___]. $\endgroup$ Aug 30, 2016 at 8:22
  • $\begingroup$ @AlexeyPopkov yes as my comment, perhaps unintelligibly, warns and posits use of WordBoundary. I will edit when I get time. Taking my daughter to her home. If you wish to edit or modify please feel free with your own attribution. $\endgroup$
    – ubpdqn
    Aug 30, 2016 at 8:25
  • $\begingroup$ @ubpdqn I've edited the answer and replaced StringContainsQ with correct method which uses StringMatchQ. $\endgroup$ Aug 30, 2016 at 8:33
2
$\begingroup$
MatchQ[e3, a_ /; First[Characters[ToString[a]]] === "e"]
$\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.