I have an array of triplets that can be approximated by the following code:

data = Table[{RandomInteger[5], RandomInteger[10], RandomChoice[{"ABC", "BCD", "DEF"}]}, {10}]

The first two elements of the triplet are data and the third element is a set of single-character flags. Let's say that the flag "D" means "don't use" so I want to delete any cases containing a "D" flag. Easy enough:

DeleteCases[data, x_ /; StringCases[x[[3]], "D"] == {"D"}]

The problem comes in for a case where a triplet contains no flags. In this case, the third element is Null:

data = Table[{RandomInteger[5], RandomInteger[10], RandomChoice[{"ABC", "BCD", "DEF", Null}]}, {10}]
DeleteCases[data, x_ /; StringCases[x[[3]], "D"] == {"D"}]

The StringCases function throws an error whenever it attempts to compare Null to "D". I would like to avoid this error message without using something like Quiet just in case there are other errors that shouldn't be hidden.

So the question is: how does one formulate a substring search that returns False instead of throwing an error if the variable passed does not have a Head of String?


1 Answer 1


You could use a pattern which specifically requires a string in the last position of the triplet:

DeleteCases[data, {__, s_String} /; StringCases[s, "D"] == {"D"}]


As Silvia has quite rightly pointed out, it is better to use StringMatchQ to check for the "D". Not only is it likely to be faster, it will work with strings containing more than one "D".

DeleteCases[data, {__, s_String} /; StringMatchQ[s, ___ ~~ "D" ~~ ___]
DeleteCases[data, {__, s_String} /; StringMatchQ[s, "*D*"]
  • $\begingroup$ +1 You beat me! I'll delete mine.. btw I think {__,s_String}/;StringMatchQ[s, ___ ~~ "D" ~~ ___] would be faster. $\endgroup$
    – Silvia
    Jun 4, 2013 at 13:38
  • $\begingroup$ @Silvia thanks for the alternative suggestion. My database is far too small at the moment to worry about speed, but one never knows how these things grow. $\endgroup$ Jun 4, 2013 at 13:47
  • $\begingroup$ @bobthechemist In fact I just tested it, and there isn't a big difference in time between your version and mine. $\endgroup$
    – Silvia
    Jun 4, 2013 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.