5
$\begingroup$

I want to select all the words in a text that have a specific number of letters. This is the way I am doing it now.

text = Import["https://en.wikipedia.org/wiki/Google"];

nletters = 15;

Select[StringCases[text, LetterCharacter ..], StringLength @ # == nletters &]

Is there any way to do it using only string patterns?

$\endgroup$
  • 1
    $\begingroup$ Can you give us an example of text that doesn't require us to import from the web? You are more likely to get an answer if you edit your question to replace the Import with an actual string. $\endgroup$ – m_goldberg Feb 26 '18 at 3:52
7
$\begingroup$

Use a regular expression. For example:

StringCases[
    ExampleData[{"Text", "DeclarationOfIndependence"}],
    RegularExpression["\\b[a-zA-Z]{15}\\b"]
]

{"undistinguished", "Representatives"}

$\endgroup$
6
$\begingroup$
StringCases[text, WordBoundary ~~ Repeated[LetterCharacter, {15}] ~~ WordBoundary] 

{"discontinuation", "Internationally", "InformationWeek", "Anticompetitive", "InformationWeek", "Environmentally", "Transliteration", "InterActiveCorp"}

StringCases[text,  WordBoundary ~~ x : LetterCharacter .. ~~ WordBoundary /; 
  StringLength[x] == 15]

{"discontinuation", "Internationally", "InformationWeek", "Anticompetitive", "InformationWeek", "Environmentally", "Transliteration", "InterActiveCorp"}

$\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.