Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Pattern matching question and answer

  • To: mathgroup at
  • Subject: [mg63062] Re: Pattern matching question and answer
  • From: dh <dh at>
  • Date: Tue, 13 Dec 2005 03:40:43 -0500 (EST)
  • References: <dnir79$9ur$>
  • Sender: owner-wri-mathgroup at

Hi Matt,
your problem is that you want to use the machanism of pattern matching 
but you specify your condition not as a pattern, but as a string-pattern.
One way to solve this problem would be to use pattern matching, but 
attaching a condition to the pattern. This condition can then contain 
the string-pattern.

Cases[expr, _ x_ /; StringMatchQ[
     ToString[x], CharacterRange["x", "z"] ~~ "0"]]


Matt wrote:
> Hello,
>   I recently was going to post this question:
> *******QUESTION START*******
> Is there a way to specify a pattern within an expression that can
> specify certain alpha-numeric combinations?
> e.g.
> expr = y0*y^2 + z0*z^2 + x0*x^2 + a1*a^2 + b1*b^2;
> If I wanted to use Cases (or whatever is deemed appropriate to
> accomplish the task) to return a list of only the parts of expr that
> are multiplied by a variable of the form 'letter'zero (i.e. x0,y0,z0),
> how would I do this?
> I could do this:
> Cases[expr, Times[x0,_]]
> Cases[expr, Times[y0,_]]
> Cases[expr, Times[z0,_]]
> But what I'm looking for would be a pattern that specifies a single
> character followed by a zero.  In regular expression syntax, if I were
> dealing with a text file, I might use something like this:
> [A-Za-z]0
> or like this
> [xyz]0
> So, my Cases statement would be able to grab all three matches like
> this (if it were supported):
> Cases[expr, Times[[xyz]0,_]]
> *******QUESTION END*******
> But before I got around to posting, I came up with a solution.  First
> off, once again, I'm impressed with Mathematica's flexibility, but I was
> wondering if there's better or more intuitive way to accomplish the
> task?
> Solution:
> Remove[expr, x0, x, y0, y, z0, z]
> expr = x0*x^2 + x00*x0^2 + y0*y^2 + z0*z^2 + x0*Sin[x]
> Cases[expr, _^_*(x:_Symbol?(StringMatchQ[ToString[#1],
> RegularExpression["[xy]0"]] & ))]
> I could also use this:
> Cases[expr, _*(x:_Symbol?(StringLength[ToString[#1]] == 2 & ))]
> if I were interested in identifiers of length 2.
> Thanks,
> Matt

  • Prev by Date: Why is y a local variable here?
  • Next by Date: Re: Pattern matching question and answer
  • Previous by thread: Re: Pattern matching question and answer
  • Next by thread: Re: Pattern matching question and answer