I searched and tried different solutions on SE but nothing worked.

I have two lists and would like to remove items from list1 that have a PARTIAL match with items in list2. I'm new to this.

I tried this but it didn't filter anything out

Select[list1, ! MemberQ[list2, #] &]

I also tried with DeleteCases and StringMatchQ but only got various errors. I tried a few solutions from SE but none worked for my specific case.

list1 = {"http://www.domain.com/research", "http://www.domain.com/signup", "tel:5559986644", "mailto:info@domain.com"}

list2 = {"tel:", "mailto:"}

results = {"http://www.domain.com/research", "http://www.domain.com/signup"}

Thank you in advance

Cases[_?(Not@*StringContainsQ[Alternatives @@ list2])]@list1
DeleteCases[_?(StringContainsQ[Alternatives @@ list2])]@list1
Select[list1, Not @* StringContainsQ[Alternatives @@ list2]]

all give

{"http://www.domain.com/research", "http://www.domain.com/signup"}

You can also use the pattern _?(StringMatchQ[#, "*" ~~ Alternatives @@ list2 ~~ "*"]&), or _?(StringMatchQ["*" ~~ Alternatives @@ list2 ~~ "*"]), e.g.,

DeleteCases[list1, _?(StringMatchQ[#,"*" ~~ Alternatives @@ list2 ~~"*"]&)]
DeleteCases[list1, _?(StringMatchQ["*" ~~ Alternatives @@ list2 ~~"*"])]

same result

  • $\begingroup$ This is great, but I could have explained that keywords are not necessarily at the start of the string. They should match anywhere in the string. Some URL values may be domain.com/signup and the keyword would be "signup" to filter those out. Right now using DeleteCases[list1, _?(StringMatchQ[#,Alternatives @@ list2~~"*"]&)] deletes everything. $\endgroup$
    – Sam B
    May 20 '19 at 13:27
  • $\begingroup$ @SamB, change StringStartsQ to StringContainsQ and StringMatchQ[#,Alternatives @@ list2~~"*"]& to StringMatchQ[#,"*"~~Alternatives @@ list2~~"*"]& $\endgroup$
    – kglr
    May 20 '19 at 13:43
  • $\begingroup$ list1 = {"http://www.domain.com/research", "http://www.domain.com/signup", "tel:5559986644", "mailto:info@domain.com", "http://www.domain.com/departments"}; list2 = {"tel:", "mailto:", "signup"}; Select[list1, _?(StringContainsQ[#, "*" ~~ Alternatives @@ list2 ~~ "*"] &)] Out = { } $\endgroup$
    – Sam B
    May 20 '19 at 13:50
  • 1
    $\begingroup$ @SamB, you need to use Select[list1, StringContainsQ[Alternatives @@ list2] ] or Select[list1, StringMatchQ[#,"*"~~Alternatives @@ list2~~"*"]& ] (or Select[list1, StringMatchQ["*"~~Alternatives @@ list2~~"*"] ]). $\endgroup$
    – kglr
    May 20 '19 at 14:04
  • $\begingroup$ Thank you @kglr! The final thing I did to get what I wanted was this: DeleteCases[list1,_?( StringContainsQ[Alternatives @@ list2])] $\endgroup$
    – Sam B
    May 20 '19 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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