[Solved] regex to match string with a minimum number of words


Hmm, you could use the character class \S+ to designate a word.

\S is equivalent to [^\s] which is itself equivalent to [^ \v\t\f\n\r] (in order I typed them: white space, vertical tab, horizontal tab, form feed, newline, carriage return).

[^ ... ] indicates a negated class, where all characters will be matched, except those inside the class.

Now, for what you’re trying to do, I would rather use re.match like so:

re.match(r'\s*\S+(?:\s+\S+){X-1,}', text_to_validate)

(?:\s+\S+) matches space(s) followed by a word.

{X-1,} means that the group (?:\s+\S+) should appear at least X-1 times to match. If X=4, then it becomes {3,}.

ideone demo


Alternate, split on spaces and count the number of elements:

re.split(r"\s+", text_to_validate)

ideone demo

7

solved regex to match string with a minimum number of words