Re: Pattern matching question and answer
- To: mathgroup at smc.vnet.net
- Subject: [mg63069] Re: [mg63054] Pattern matching question and answer
- From: Bob Hanlon <hanlonr at cox.net>
- Date: Tue, 13 Dec 2005 03:40:51 -0500 (EST)
- Reply-to: hanlonr at cox.net
- Sender: owner-wri-mathgroup at wolfram.com
expr=y0*y^2+z0*z^2+x0*x^2+a1*a^2+b1*b^2+q0;
var=ToExpression[#<>"0"&/@
Cases[CharacterRange["A","z"],_?LetterQ]];
Flatten[Cases[expr,#*_.,1]&/@var]
{q0, x^2*x0, y^2*y0, z^2*z0}
Note use of _. to handle default (e.g., q0 term).
Bob Hanlon
>
> From: "Matt" <anonmous69 at netscape.net>
To: mathgroup at smc.vnet.net
> Date: 2005/12/11 Sun PM 10:25:31 EST
> Subject: [mg63069] [mg63054] Pattern matching question and answer
>
> 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
>