MathGroup Archive 2005

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

Search the Archive

Pattern matching question and answer

  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?


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:

or like this


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

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.



  • Prev by Date: Puzzling HoldFirst behaviour
  • Next by Date: Fonts and PSTOEDIT
  • Previous by thread: Puzzling HoldFirst behaviour
  • Next by thread: Re: Pattern matching question and answer