1
$\begingroup$

Say I have a list of strings L , L2= "some_text-to-delete" and I want to delete all the Li that match with "text" or "delete" DeleteCase only gives the ones that match exactly...

$\endgroup$
3
  • $\begingroup$ Use StringMatchQ and string patterns: DeleteCases[yourlist,z_/;StringMatchQ[z,___~~"text"~~___,IgnoreCase->True] etc $\endgroup$ Jul 14, 2014 at 20:40
  • $\begingroup$ What the z_/ does? $\endgroup$
    – Kafkarudo
    Jul 14, 2014 at 20:44
  • 2
    $\begingroup$ z_ is a pattern. /; is a condition $\endgroup$ Jul 14, 2014 at 20:44

1 Answer 1

1
$\begingroup$

Here are some suggestions:

let list={"element1","element2","text","text","element5"}

DeleteCases[list, x_ /; StringMatchQ[x, "*text*", IgnoreCase -> True]]    

Select[list, StringFreeQ[#, "text", IgnoreCase -> True] &]    

Extract[list,Position[list,x_String/;StringFreeQ[x,"text",IgnoreCase->True]]]

{"element1", "element2", "element3"}

For a timing test, if we do list2 = Flatten@Table[list, {100000}];

(t1=DeleteCases[list2,x_/;StringMatchQ[x,"*text*",IgnoreCase->True]])//AbsoluteTiming//First
(t2=Select[list2,StringFreeQ[#,"text",IgnoreCase->True]&])//AbsoluteTiming//First
(t3=Extract[list2,Position[list2,x_String/;StringFreeQ[x,"text",IgnoreCase->True]]])//AbsoluteTiming//First
t1==t2==t3

True

0.624

0.882

1.110

So t1 is the best.

$\endgroup$
1
  • 1
    $\begingroup$ Thank you for that answer, it really help me,you do know how to teach :) $\endgroup$
    – Kafkarudo
    Jul 20, 2014 at 22:13

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