3
$\begingroup$

I have a string like this:

string="there is a humble-bee in Hanna's garden";

Now I want to exclude those words that contain "-" and "'". My own solution would be:

StringDelete[string,Cases[StringSplit[string," "], _?(StringContainsQ[#, {"'", "-"}] &)]]

so the outcome is:

"there is a in garden"

But I was wondering whether there is a more elegant solution?

$\endgroup$
1
  • 3
    $\begingroup$ Select[StringSplit@string, StringMatchQ[#, WordCharacter ...] &] - you can pick out the words that don't completely contain WordCharacters into a list. $\endgroup$
    – flinty
    Dec 3 '21 at 12:25
5
$\begingroup$
StringDelete[string, WordCharacter .. ~~ "'" | "-" ~~ WordCharacter ..]
"there is a  in  garden"
StringRiffle @ Select[StringFreeQ["'" | "-"]] @ StringSplit[string]
"there is a in garden"
$\endgroup$
3
$\begingroup$

You can give a string pattern to "StringDelete" like:

string = "there is a humble-bee in Hanna's garden";
pat = WordCharacter ... ~~ ("-" | "'") ~~ WordCharacter ...;
StringDelete[string, pat]
(*"there is a  in  garden"*)
$\endgroup$

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.