MathGroup Archive 2012

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

Search the Archive

Re: How to coerce a string pattern to an ordinary pattern?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg124394] Re: How to coerce a string pattern to an ordinary pattern?
  • From: "Oleksandr Rasputinov" <oleksandr_rasputinov at hmamail.com>
  • Date: Wed, 18 Jan 2012 06:00:33 -0500 (EST)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <jf3cbd$ni4$1@smc.vnet.net>

On Tue, 17 Jan 2012 08:43:25 -0000, Andrew DeYoung  
<adeyoung at andrew.cmu.edu> wrote:

> Hi,
>
> How do I coerce a string pattern to an ordinary pattern?  For example,
> I might want to select those elements of a list that are pairs of
> strings, where the first string matches the string pattern
> "["~~___~~"]".
>
> Thank you so much for your time.
>
> Andrew DeYoung
> Carnegie Mellon University
>

In general you can't, because string patterns and symbolic patterns are  
fundamentally different. Instead you could, e.g., write a symbolic pattern  
that takes this into account and matches string patterns where necessary  
using StringMatchQ etc. For instance, a pattern that works for your  
example is:

patt = {_String?(StringMatchQ[#, "[" ~~ ___ ~~ "]"] &), _String}

lst = {{1, "[a]"}, {"[b]", "2"}, {"[c]", 3}, {"[d]", "4"}, {"5", "[e]"}}

In :=
Cases[lst, patt]

Out =
{{"[b]", "2"}, {"[d]", "4"}}

Another possible approach would be to use ToString on the whole expression  
and match exclusively using string patterns. However, I wouldn't  
personally recommend this method, mainly because string patterns are less  
flexible than symbolic ones.



  • Prev by Date: Re: Is there any efficient easy way to compare two lists with the same length with Mathematica?
  • Next by Date: Re: Cross reference - a further question.
  • Previous by thread: Re: How to coerce a string pattern to an ordinary pattern?
  • Next by thread: Example of Cellular potts model in mathematica