Number of words per line

How can I match the number of words per line and then 5 using regex?

Input1: stack over flow => the regex will not match anything

Input2: stack over flow stack over => the regex will match this string

I tried counting spaces with /\/s/, but that did not help me because I only needed to match strings without words> 5

Also I do not want to use spaces split.

+4
source share
2 answers

I would rely on whitespace / non-whitespace patterns and allow spaces / leading spaces:

^\s*\S+(?:\s+\S+){4,}\s*$

Watch the demo

Explanation:

  • ^ - beginning of line
  • \s* - optional number of whitespace characters
  • \S+ - one or more non-white characters
  • (?:\s+\S+){4,} - 4 or more sequences of one or more whitespace characters, followed by one or more characters without spaces.
  • \s* - ()
  • $ -
+4
^ *\w+(?: +\w+){4,}$

regex.See demo.

https://regex101.com/r/cZ0sD2/15

+5

Source: https://habr.com/ru/post/1626314/


All Articles