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.
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^ *\w+(?: +\w+){4,}$
You can use this regex.See demo.
https://regex101.com/r/cZ0sD2/15
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 wordSee demo at regex101
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With