I'm looking to use DictionaryLookup to search the English dictionary for words that don't contain certain strings. For example, I want to exclude "ar" and "h" from my search, and have "far" and "hat" not appear. (I'm going to have a long list of strings, so my search result will be limited down significantly.)

Finally, I'm looking to sort these results by word length. Any help getting started doing this is much appreciated!

  • $\begingroup$ Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$
    – Mahdi
    Commented May 7, 2015 at 23:57

2 Answers 2


Something like this

words = DictionaryLookup[s__ /; StringFreeQ[s, "ar" | "h"]];

sorted = SortBy[words, StringLength];

{"a", "I", "AC", "ad", "AD", <<70772>>, "Andrianampoinimerina", 
  "buckminsterfullerene", "institutionalization", "internationalization"}
  • $\begingroup$ About twice as fast to just filter all: Select[DictionaryLookup[], ! StringMatchQ[#, "*h*" | "*ar*"] &] - and +1 $\endgroup$
    – ciao
    Commented May 8, 2015 at 0:16
  • 1
    $\begingroup$ I believe that SortBy[words, Length] should be SortBy[words, StringLength], no? $\endgroup$
    – nben
    Commented May 8, 2015 at 0:24
  • $\begingroup$ @user21382 yes, thank you! $\endgroup$
    – Greg Hurst
    Commented May 8, 2015 at 1:35

Doing this is pretty straightforward; you'll want to take a look at the documentation for Mathematica's string patterns primarily.

As an example, to use DictionaryLookup with the "ar" and "h" instance you mention, the following are basically equivalent:

matches1 = DictionaryLookup[s__ /; !StringContainsQ[s, "ar"|"h"]];
matches2 = DictionaryLookup[__?(!StringContainsQ[#, "ar"|"h"]&)];

If you have a large list of exclusions that you have loaded from a file, for example, you would want to do something like this:

list = {"h", "ar", "some", "other", "strings" (* ... *)};
matches = DictionaryLookup[s__ /; !StringContainsQ[s, Alternatives @@ list]]];

In this case, the (A @@ B) is syntactic sugar for the Apply[A, B] function and the A|B from the previous examples is just syntactic sugar for the Alternatives function, so Alternatives@@list was equivalent to "h"|"ar"|"some"|"other"|"strings".

To do the sorting, you will probably want to use the SortBy function:

sorted = SortBy[matches, StringLength];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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