Re: Pattern matching question and answer
- To: mathgroup at smc.vnet.net
- Subject: [mg63083] Re: Pattern matching question and answer
- From: "dkr" <dkrjeg at adelphia.net>
- Date: Tue, 13 Dec 2005 03:41:25 -0500 (EST)
- References: <dnir79$9ur$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
One alternative is to take full advantage of regexes by transforming
your expression into a string.
In[1]:=
expr = x0*x^2 + x00*x0^2 + a0*y^2 + z0*z^2 + x0*Sin[x] ;
I have replaced your y0 with an a0 for reasons explained below.
In[4]:=
Cases[expr, _^_*(x:_Symbol?(StringMatchQ[ToString[#1],
RegularExpression["[xa]0"]] & ))] //InputForm
Out[4]//InputForm=
{x^2*x0, a0*y^2}
In[5]:=
StringCases[ToString[expr,InputForm],
RegularExpression["\\b(\\w+\\^\\d+\\*[xa]0|[xa]0\\*\\w+\\^\\d+)\\b"]]//
ToExpression//InputForm
Out[5]//InputForm=
{x^2*x0, a0*y^2}
One drawback is that we have to be explicitly concerned about the
Orderless attribute of Times, while the regular pattern matching
involved in your approach takes this attribute into account
automatically. Using a0 rather than y0 forced us to use alternation in
the regex to account for the Orderless attribute.
dkr