Reputation: 2309
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
Reputation: 18490
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 wordUpvotes: 1
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 stringUpvotes: 10
Reputation: 67968
^ *\w+(?: +\w+){4,}$
You can use this regex.See demo.
https://regex101.com/r/cZ0sD2/15
Upvotes: 5