# How do I use DictionaryLookup to exclude words with certain phrases?

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!

• 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. May 7 '15 at 23:57

Something like this

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

Length[words]

70781

sorted = SortBy[words, StringLength];

Short[sorted]

{"a", "I", "AC", "ad", "AD", <<70772>>, "Andrianampoinimerina",
"buckminsterfullerene", "institutionalization", "internationalization"}

• About twice as fast to just filter all: Select[DictionaryLookup[], ! StringMatchQ[#, "*h*" | "*ar*"] &] - and +1
– ciao
May 8 '15 at 0:16
• I believe that SortBy[words, Length] should be SortBy[words, StringLength], no?
– nben
May 8 '15 at 0:24
• @user21382 yes, thank you! May 8 '15 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];