MathGroup Archive 2010

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

Search the Archive

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

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

In[1]:= list = {"DTEND:19260412T175900", "DTEND:20070207T050000",

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

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

In[3]:= StringCases[list, ___~~"END:"~~___]
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",
Not as expected!

But, in the end, what works is:

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

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

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,

  • 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