Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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"}]

Also

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*"]
share|improve this answer
    
+1 You beat me! I'll delete mine.. btw I think {__,s_String}/;StringMatchQ[s, ___ ~~ "D" ~~ ___] would be faster. –  Silvia Jun 4 '13 at 13:38
    
@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. –  bobthechemist Jun 4 '13 at 13:47
    
@bobthechemist In fact I just tested it, and there isn't a big difference in time between your version and mine. –  Silvia Jun 4 '13 at 13:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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