Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #7921 > unrolled thread

How to coerce a string pattern to an ordinary pattern?

Started byAndrew DeYoung <adeyoung@andrew.cmu.edu>
First post2012-01-17 08:43 +0000
Last post2012-01-18 11:03 +0000
Articles 2 — 2 participants

Back to article view | Back to comp.soft-sys.math.mathematica


Contents

  How to coerce a string pattern to an ordinary pattern? Andrew DeYoung <adeyoung@andrew.cmu.edu> - 2012-01-17 08:43 +0000
    Re: How to coerce a string pattern to an ordinary pattern? "Oleksandr Rasputinov" <oleksandr_rasputinov@hmamail.com> - 2012-01-18 11:03 +0000

#7921 — How to coerce a string pattern to an ordinary pattern?

FromAndrew DeYoung <adeyoung@andrew.cmu.edu>
Date2012-01-17 08:43 +0000
SubjectHow to coerce a string pattern to an ordinary pattern?
Message-ID<jf3cbd$ni4$1@smc.vnet.net>
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

[toc] | [next] | [standalone]


#7971

From"Oleksandr Rasputinov" <oleksandr_rasputinov@hmamail.com>
Date2012-01-18 11:03 +0000
Message-ID<jf68tc$g9r$1@smc.vnet.net>
In reply to#7921
On Tue, 17 Jan 2012 08:43:25 -0000, Andrew DeYoung  
<adeyoung@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.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.soft-sys.math.mathematica


csiph-web