Message Boards Message Boards

0
|
9058 Views
|
8 Replies
|
7 Total Likes
View groups...
Share
Share this post:

[?] Delete cases that contain a certain string?

Posted 5 years ago

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

POSTED BY: Andrew Burnett
8 Replies
Posted 5 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

POSTED BY: Michael Helmle
Posted 5 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 BY: Andrew Burnett
Posted 5 years ago

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

Cheers Andy

POSTED BY: Andrew Burnett
Posted 5 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 BY: Rohit Namjoshi
    domains = {"aa.com", "bb.com", "aa.edu", "baa.com", "cc.bla"};
    DeleteCases[domains, "aa.com"]
(* {"bb.com", "aa.edu", "baa.com", "cc.bla"} *)
Posted 5 years ago
domains = {"aa.com", "bb.com", "aa.edu", "baa.com", "cc.bla"}
DeleteCases[domains, _?(StringContainsQ[#, "aa.com"] &)]
POSTED BY: Michael Helmle

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 BY: Henrik Schachner
Posted 5 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.

POSTED BY: Andrew Burnett
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