MathGroup Archive 2010

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

Search the Archive

Cases vs. StringCases vs. Select and StringMatchQ vs. StringFreeQ

  • To: mathgroup at smc.vnet.net
  • Subject: [mg111153] Cases vs. StringCases vs. Select and StringMatchQ vs. StringFreeQ
  • From: David Latin <d.latin at gmail.com>
  • Date: Thu, 22 Jul 2010 05:41:56 -0400 (EDT)

Hello,
I am currently working on manipulating data in "vCard"-like format, and have
become confused by the actions of the Cases, StringCases and Select
functions.
Consider the small list:

In[1]:= list = {"DTEND:19260412T175900", "DTEND:20070207T050000",
"END:VCALENDAR", "MM"} ;

In[2]:= Cases[list, ___~~"END:"~~___]
Out[2]= {}
So pattern-matching obviously does not work with Cases for a list of
strings.

The documentation for Cases does not refer to patterns in strings, so I
tried

In[3]:= StringCases[list, ___~~"END:"~~___]
Out[3]=
{{"DTEND:19260412T175900"},{"DTEND:20070207T050000"},{"END:VCALENDAR"},{}}
The problem here is that empty elements can be returned.

So next I tried

In[4]:= Select[list, ___~~"END:"~~___]
Out[4]= {}
Obviously not working.

Next I tried

In[5]:= Select[ list, StringMatchQ[#, "*END:*"] & ]
Out[5]= {"DTEND:19260412T175900", "DTEND:20070207T050000", "END:VCALENDAR"}

This is fine.
But what if I only want the "END:" lines and not the "DTEND:" lines ?

It may be appropriate to make use of

In[6]:= Select[ list, StringFreeQ[#, "*DTEND:*"] & ]
Out[6]= {"DTEND:19260412T175900", "DTEND:20070207T050000", "END:VCALENDAR",
"MM"}
Not as expected!

But, in the end, what works is:

In[7]:= Select[ list, StringMatchQ[#, "*END:*"] && ! StringMatchQ[#,
"*DTEND:*"] & ]
Out[7]= {"END:VCALENDAR"}

I know I could have used "END*" instead of "*END*", but that's not the point
here.

My questions then are:
Why doesn't Cases work for a list of strings ?
Why doesn't Select work for patterns with the ~~ operator ?
Why doesn't StringFreeQ act in the same way as !StringMatchQ ?

Any help over this confusion would be very much appreciated!
Thank you,
  David


  • Prev by Date: Re: FindRoot
  • Next by Date: Re: Show left hand side
  • Previous by thread: Re: surprising comparison of Mathematica 5.2 and 7.0
  • Next by thread: Re: Cases vs. StringCases vs. Select and StringMatchQ vs. StringFreeQ