Search code examples
regexruby

A Regex to ensure that a string contains at least two words


Given a string of one or more words, I need a regex which returns true if the string contains two or more words - any words. My current solution is:

([\w\']+ ){1,}

which works on the basis that a one-word string (which has been stripped) won't have a trailing space, implying there must be another word if the string contains a space.

The solution seems quirky and there has to be a better answer.


Solution

  • Please use this regular expression regex = (\p{L}+)(\W+\p{L}+)+ . The regex will ensures that the string has at least two words separated by one or more spaces and also check punctuation between words and accented characters and unicode letters.