Message Boards Message Boards

GROUPS:

[?] Delete cases that contain a certain string?

Posted 2 years ago
4127 Views
|
8 Replies
|
7 Total Likes
|

I am struggling with what I believe is a very simple problem. I have a list of email domains

domains = {"aa.com","bb.com","aa.edu"...}

I want to delete all occurrences of "aa.com". So, I tried

DeleteCases[StringContainsQ[#, "aa.com"] &] /@ domains

Sadly, this doesn't work. Could some kind soul enlighten me on what I did wrong? Cheers Andy

8 Replies
Posted 2 years ago

After a bit of googling I have learned that I can do the following

Delete[domains, Position[domains, "aa.com"]]

However, I think this only works if the element exactly matches the pattern, so my revised question is how would I search for a substring within an element. In effect I want to do something like this

Position[domains, StringMatchQ[#, "aa.com"] &]

But I can't quite work out how to do this.

You probably need StringContainsQ:

domains = {"aa.com", "bb.com", "aa.edu", "baa.com", "cc.bla"};
Select[domains, ! StringContainsQ[#, "aa.com"] &]
(*  Out:  {"bb.com","aa.edu","cc.bla"}  *)
Posted 2 years ago
domains = {"aa.com", "bb.com", "aa.edu", "baa.com", "cc.bla"}
DeleteCases[domains, _?(StringContainsQ[#, "aa.com"] &)]
Posted 2 years ago

Hi Michael, _?(StringContainsQ[#, "aa.com"] &) Seems to do exactly what I need. However, I am not entirely clear how it works. The help seems to suggest that _?() means match any expression and then return true if the expression in the parenthesis evaluates to true. Have I understood that correctly?

Cheers Andy

Posted 2 years ago

Hi Andy, please have look at "PatternTest" in the documentation. DeleteCases requires a pattern as a second argument, and _?test is the pattern that matches everything provided the condition "test" evaluates to True. The parenthesis are required to control the sequence of evaluation due to the high precedence of the ? operator (also described in the docu).

Regards, Michael

    domains = {"aa.com", "bb.com", "aa.edu", "baa.com", "cc.bla"};
    DeleteCases[domains, "aa.com"]
(* {"bb.com", "aa.edu", "baa.com", "cc.bla"} *)
Posted 2 years ago

If you have a list of names that you want to delete

domains = {"aa.com", "bb.com", "aa.edu", "baa.com", "cc.bla"};
deletes = {"aa.com", "cc.bla"};
DeleteCases[domains, Alternatives @@ deletes]
(* {"bb.com", "aa.edu", "baa.com"} *)
Posted 2 years ago

Thanks Rohit. You have given me lots to dive into here.

Cheers Andy

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract