RockNinja
RockNinja

Reputation: 2309

Count number of words in a string

How can I match the number of words in a string to be > 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 have tried counting the spaces with /\/s/ but that didn't really helped me, because I need to match only strings with no of words > 5

Also I don't want to use split by spaces.

Upvotes: 11

Views: 22263

Answers (3)

bobble bubble
bobble bubble

Reputation: 18490

To check if there are at least 5 words in string:

(?:\w+\W+){4}\b

See demo at regex101

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

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

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

See demo

Explanation:

  • ^ - start of string
  • \s* - optional any number of whitespace symbols
  • \S+ - one or more non-whitespace symbols
  • (?:\s+\S+){4,} - 4 or more sequences of one or more whitespace symbols followed with one or more non-whitespace symbols
  • \s* - zero or more (optional) trailing whitespace symbols
  • $ - end of string

Upvotes: 10

vks
vks

Reputation: 67968

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

You can use this regex.See demo.

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

Upvotes: 5

Related Questions