Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*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

Pattern matching question and answer

  • To: mathgroup at smc.vnet.net
  • Subject: [mg63054] Pattern matching question and answer
  • From: "Matt" <anonmous69 at netscape.net>
  • Date: Sun, 11 Dec 2005 22:25:31 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

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: Puzzling HoldFirst behaviour
  • Next by Date: Fonts and PSTOEDIT
  • Previous by thread: Puzzling HoldFirst behaviour
  • Next by thread: Re: Pattern matching question and answer