Re: Question about DeleteCases to remove list elements based on first character
- To: mathgroup at smc.vnet.net
- Subject: [mg124323] Re: Question about DeleteCases to remove list elements based on first character
- From: "Scot T. Martin" <smartin at seas.harvard.edu>
- Date: Tue, 17 Jan 2012 03:21:00 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
Andrew, there are several ways to get this result, and you were almost there. Here's one example below. The key point is to recognize that you have a list (i.e., not a String action) for which you wish to do a test (i.e., by String actions) on the list elements.
In[1]:= ?Pick
Pick[list,sel] picks out those elements of list for which the corresponding element of sel is True.
In[2]:= ?StringMatchQ
StringMatchQ["string",patt] tests whether "string" matches the string pattern patt.
In[3]:= list = {"abc", ";def", "ghi", ";jkl", "; mno", "pqr;X"}
Out[3]= {"abc", ";def", "ghi", ";jkl", "; mno", "pqr;X"}
In[4]:= sel = Not[StringMatchQ[#, ";" ~~ __]] & /@ list
Out[4]= {True, False, True, False, False, True}
In[5]:= Pick[list, sel]
Out[5]= {"abc", "ghi", "pqr;X"}
________________________________________
From: Andrew DeYoung [adeyoung at andrew.cmu.edu]
Sent: Monday, January 16, 2012 17:06
To: mathgroup at smc.vnet.net
Subject: [mg124323] Question about DeleteCases to remove list elements based on first character
Hi,
I have a list of strings in which some elements begin with the ";"
character and some do not. The ";" character indicates a program
comment, so I wish to drop all elements in the list that begin with
the ";" character.
As a simplified example, suppose I have the following list S:
S = {"abc", ";def", "ghi", ";jkl", "; mno", "pqr;X"}
I wish to drop from S all elements that begin with ";". So, I want to
obtain:
{"abc", "ghi", "pqr;X"}
Will you please help me know how to do this? Can this be done with
DeleteCases? For example, I tried:
DeleteCases[S, StringTake[#, 1] == ";"&]
and
DeleteCases[S, ";" ~~ __]
but I am wrong: these do not work. Can you please help me?
Thanks so much.
Andrew DeYoung
Carnegie Mellon University