Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of words in a string

Tags:

regex

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.

like image 462
RockNinja Avatar asked Jan 28 '16 08:01

RockNinja


3 Answers

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
like image 51
Wiktor Stribiżew Avatar answered Oct 31 '22 10:10

Wiktor Stribiżew


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

You can use this regex.See demo.

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

like image 23
vks Avatar answered Oct 31 '22 08:10

vks


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

(?:\w+\W+){4}\b
  • (?:\w+\W+){4} 4 words separated by non word characters
  • \b followed by a word boundary -> requires a 5th word

See demo at regex101

like image 43
bobble bubble Avatar answered Oct 31 '22 09:10

bobble bubble