I want to check if a string consists of n or more words.

I use the following regex to check for 3 words, but the match returns true?

:echo '  hello world  ' =~ '^\(\s\{-}\w\+\)\{-3,}'

How to make regex matching "n" or more words?


I don't know if it's correct, but to check if a string contains 3 words or more I would type this :

:echo 'some random string' =~ '\v\s*(\w+\s+){2,}\w+\s*'

For 4 words or more :

:echo 'some random string' =~ '\v\s*(\w+\s+){3,}\w+\s*'


Edit: Peter Rincker's answer seems much better and shorter :


Not sure but I suppose it can be read as :
very magic mode enabled (\v), a word (\w+) followed by either a whitespace (\s+) or (|) the end of the string ($), everything being repeated 3 or more times ({3,}).

| improve this answer | |
  • 3
    Shorter regex: \v(\w+(\s+|$)){3,} – Peter Rincker Nov 6 '15 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.