# Pattern Match symbols that begin with same letter?

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?

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

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.

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" ~~ ___]]

• 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" ~~ _]]. Aug 30, 2016 at 6:34
• @Karsten7. my bad habits die hard...and I have been too slow to recognize and apply the operator forms. :) Aug 30, 2016 at 6:38
• Note that StringContainsQ["aer", "e" ~~ _] returns True what isn't what you want. The correct test is StringMatchQ["aer", "e" ~~ ___]. Aug 30, 2016 at 8:22
• @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. Aug 30, 2016 at 8:25
• @ubpdqn I've edited the answer and replaced StringContainsQ with correct method which uses StringMatchQ. Aug 30, 2016 at 8:33
MatchQ[e3, a_ /; First[Characters[ToString[a]]] === "e"]