Re: Pattern matching
- To: mathgroup at smc.vnet.net
- Subject: [mg33940] Re: Pattern matching
- From: Janus Wesenberg <nil at holeinground.net>
- Date: Wed, 24 Apr 2002 01:21:47 -0400 (EDT)
- References: <aa3fq4$7tv$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
John Leary wrote: > Greetings > > Can you help me please - there must be a simple solution to this problem, > but I can't find it. > > From a list of character strings and a list of templates, I need to > produce a list of all strings that match any of the templates. For example: > > listData={"18K0F3C--" , "2K40GXX--" , "400HGXX--" , "5M00G1F--" , "960KG1D--"} > listTemplates={"???H?????" , "???K?????"} > result={"400HGXX--","960KG1D--"} > > In the templates, ? is a wild-card that represents a single character. > The data strings contain only alpha-numeric characters and hyphens - no > other characters. > There are no special requirements for the result: duplication and random > order are acceptable. Here's one way to do it: implement a matchTemplatesQ function that yields true if any of the templates is matched. Note that matchTemplatesQ depends on listTemplates which is not given as an argument -- Personally I don't have a problem with polution of the global namespace, but you'll probably get some followup on this... matchTemplatesQ[s_String] := Or @@ ((MatchQ[Characters[s], Characters[#] /. "?" -> _]) & /@ listTemplates) Select[listData, matchTemplatesQ] Out: {"400HGXX--", "960KG1D--"} The mystical @@, /@ and ( # )& stuff is just a shorthand for Apply, Map and Function, which you might want to look up in help. Hope this helps /Janus-- || Janus Wesenberg _||_ www.ifa.au.dk/~jaw Ph.D. Student at Quantop ( ) jaw@^^^^^^^^^ \ / ||